Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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?

Thanks.

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.

like image 979
jyavenard Avatar asked Jun 02 '12 01:06

jyavenard


2 Answers

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;
like image 99
James McNellis Avatar answered Sep 28 '22 16:09

James McNellis


As K-ballo said, The code is equivalent to:

MyStruct test_struct = {
    "buffer",
    test_func1
};

But since you are using C++, you should considere writing and using constructors for MyStruct:

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

    MyStruct(const char *n,
        int (*f1)(void) = NULL,
        int (*f2)(void) = NULL,
        int (*f3)(void) = NULL) : name(n), func1(f1), func2(f2), func3(f3) {}
};

Note that in C++ you do not need to typedef it to MyStruct, you can just use MyStruct (without the struct keyword) even without the typedef.

like image 25
fbafelipe Avatar answered Sep 28 '22 17:09

fbafelipe