The company I work at is initializing all of their data structures through an initialize function like so:
//the structure
typedef struct{
int a,b,c;
} Foo;
//the initialize function
InitializeFoo(Foo* const foo){
foo->a = x; //derived here based on other data
foo->b = y; //derived here based on other data
foo->c = z; //derived here based on other data
}
//initializing the structure
Foo foo;
InitializeFoo(&foo);
I've gotten some push back trying to initialize my structs like this:
//the structure
typedef struct{
int a,b,c;
} Foo;
//the initialize function
Foo ConstructFoo(int a, int b, int c){
Foo foo;
foo.a = a; //part of parameter input (inputs derived outside of function)
foo.b = b; //part of parameter input (inputs derived outside of function)
foo.c = c; //part of parameter input (inputs derived outside of function)
return foo;
}
//initialize (or construct) the structure
Foo foo = ConstructFoo(x,y,z);
Is there an advantage to one over the other?
Which one should I do, and how would I justify it as a better practice?
InitializeFoo()
is a constructor. The only difference from a C++ constructor is, that thethis
pointer is passed explicitly rather than implicitly. The compiled code ofInitializeFoo()
and a corresponding C++Foo::Foo()
is exactly the same. – cmaster - reinstate monica Jul 20 '15 at 19:23const Foo
objects, as inFoo const foo = ConstructFoo(x,y,z);
This cannot be done with the first approach, unless you wrap it into another function (you can implement either approach using the other). – dyp Jul 20 '15 at 19:54