jyavenard jyavenard - 1 year ago 76
C Question

What is the C++ equivalent to C's designated initializers?

You can declare a structure in C like so:

typedef struct MyStruct {
const char *name;
int (*func1)(void);
int (*func2)(void);
int (*func3)(void);
} MyStruct;

int test_func2(void) {
return 0;

MyStruct test_struct = {
.name = "buffer",
.func2 = test_func2,

This is quite handy for only defining particular members, all the other ones being set to 0/NULL.

Edit: in particular, this allows to not know the details of how MyStruct is defined, so it can change internally, adding new members etc.. without ever breaking code using this type.

This wouldn't compile with a C++ compiler however, getting error:

test.c:23: error: expected primary-expression before ‘.’ token
test.c:24: error: expected primary-expression before ‘.’ token

Is there an equivalent C++ declaration achieving the same?


Edit: @chris I can tell you don't understand :)
And It's quite obvious that most other people commenting on what syntax I should have used, how the structure should have been defined etc.. have completely missed the point. This isn't about the correct way to define a structure, this snippet was only there to provide a context.

As for code equivalence,
Say somewhere in your code you did:

MyStruct blah = { NULL, NULL, func2 };

Now MyStruct change its definition to be:

typedef struct MyStruct {
const char *name;
int (*func4)(void);
int (*func1)(void);
int (*func2)(void);
int (*func3)(void);
} MyStruct;

Your code will still compile just fine, but has introduced a serious regression : instead of setting func2 like it used to, you would now initialise func1 member...

The question was about is there C++ designated initializers equivalent: there isn't. problem closed.

Answer Source

No, C++ does not support C99's designated initializers. If you want to set individual members by name, you'll need to do it via assignment, e.g.

MyStruct test_struct = MyStruct();
test_struct.name  = "buffer";
test_struct.func1 = test_func1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download