Initialise C-structs in C++
NickName:dangerousdave Ask DateTime:2012-01-20T22:22:54

Initialise C-structs in C++

I am creating a bunch of C structs so i can encapsulate data to be passed over a dll c interface. The structs have many members, and I want them to have defaults, so that they can be created with only a few members specified.

As I understand it, the structs need to remain c-style, so can't contain constructors. Whats the best way to create them? I was thinking a factory?

Copyright Notice:Content Author:「dangerousdave」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/8942808/initialise-c-structs-in-c

Answers
spraff 2012-01-20T14:25:11

struct Foo {\n static Foo make_default ();\n};\n\n\nA factory is overkill. You use it when you want to create instances of a given interface, but the runtime type of the implementation isn't statically known at the site of creation.",


Goz 2012-01-20T14:48:26

The C-Structs can still have member functions. Problems will, however, arise if you start using virtual functions as this necessitates a virtual table somewhere in the struct's memory. Normal member functions (such as a constructor) don't actually add any size to the struct. You can then pass the struct to the DLL with no problems.",


Begemoth 2012-01-20T14:32:20

I would use a constructor class:\n\nstruct Foo { ... };\nclass MakeFoo\n{\n Foo x;\npublic:\n MakeFoo(<Required-Members>)\n {\n <Initalize Required Members in x>\n <Initalize Members with default values in x>\n }\n\n MakeFoo& optionalMember1(T v)\n {\n x.optionalMember1 = v;\n }\n\n // .. for the rest option members;\n\n operator Foo() const \n {\n return x;\n }\n};\n\n\nThis allows to arbitrary set members of the struct in expression:\n\nprocessFoo(MakeFoo(1,2,3).optionalMember3(5));\n",


More about “Initialise C-structs in C++” related questions