3

In godbolt: https://godbolt.org/z/bY1a3e1Wz

the code in question is below (the error message says "error: either all initializer clauses should be designated or none of them should be" but I dont understand what it is saying..

struct A {
    int a;
    bool b;
};

struct B : A {
    long c;
};

int main(void) {
    B foo {{.a = 1, .b = false}, .c = 7};
}
Palace Chan
  • 8,845
  • 11
  • 41
  • 93
  • 3
    The code is not valid standard C++17 at all. It wasn't possible to initialize with the `.x =` designated initializer syntax before C++20. Your compiler just accepted it as a language extension and the rules for that language extension are different than the rules in standard C++20 for designated initializers. Compile with the `-pedantic` or `-pedantic-errors` flag if you don't want GCC to accept such language extensions without a warning/error. – user17732522 May 20 '23 at 04:28
  • 1
    See also: this proposed modification to C++ [P2287](https://github.com/cplusplus/papers/issues/978), which, in its latest revision, would create the syntax `B foo{.a = 1, .b = false, .c = 7};`. But it doesn't seem like it'll land for a few years... – HTNW May 20 '23 at 04:50
  • As the error message say, you either need to use designated initializers for all data, or for none. And since it's not possible to use designators for inherited sub-objects you can't use it at all. – Some programmer dude May 20 '23 at 05:02

1 Answers1

3

From what I see in the docs, it looks like this should work:

B foo = {{.a = 1, .b = false}, 7};

The reason seems to be that the first initializer is "nameless" (by order) and so the second one (c) should also be initialized by order rather than by name (it can not be designated)

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87