Initializing C Structures in C ++

I am creating a bunch of C structures, so I can encapsulate the data passed through the dll c interface. Structures have many members, and I want them to have default values, so that they can be created with only a few members.

As I understand it, structures should remain c-style, so they cannot contain constructors. What is the best way to create them? I was thinking about a factory?

+4
source share
4 answers
struct Foo { static Foo make_default (); }; 

A factory is redundant. You use it when you want to create instances of this interface, but the type of execution execution is not statically known at the place of creation.

+3
source

C Structures may still have member functions. However, problems will arise if you start using virtual functions, since this requires a virtual table somewhere in the structure's memory. Normal member functions (such as a constructor) do not actually add any size to the structure. You can pass structure to DLL without problems.

+3
source

I would use the constructor class:

 struct Foo { ... }; class MakeFoo { Foo x; public: MakeFoo(<Required-Members>) { <Initalize Required Members in x> <Initalize Members with default values in x> } MakeFoo& optionalMember1(T v) { x.optionalMember1 = v; } // .. for the rest option members; operator Foo() const { return x; } }; 

This allows arbitrary sets of structure elements in the expression:

 processFoo(MakeFoo(1,2,3).optionalMember3(5)); 
+1
source

I have an easy idea, here's how:

Create the structure as usual and create a simple function that initializes it:

 struct Foo{...}; void Default(Foo &obj) { // ... do the initialization here } 

If you have several structures, in C ++ you are allowed to overload the function, so you can have many functions called "default", each of which initializes its own type, for example:

 struct Foo { //... }; struct Bar { //... }; void Default(Foo &obj) {...} void Default(Bar &obj) {...} 

The C ++ compiler will know when to call the first or second overload based on this parameter. It makes a reference to any parameter that you give it, so any changes made to obj will be reflected in the variable that you put as the parameter.

Edit: I also have an idea how to specify some parameters, you can do this using the default parameters. Here's how it works:

For example, you use the following function; You can specify default values ​​for such parameters:

 void Default (Foo &obj, int number_of_something = 0, int some_other_param = 10) { ... } 
+1
source

Source: https://habr.com/ru/post/1392053/


All Articles