Designated Initializers and Aggregates in C 20
In C 20, designated initializers provide a concise way to initialize aggregate types by explicitly specifying the member to be initialized. However, this syntax has limitations when it comes to initializing inherited classes.
Consider the following code snippet:
<code class="cpp">struct Person { std::string name; std::string surname; unsigned age; }; struct Employee : Person { unsigned salary; };</code>
Both Person and Employee are aggregates, but the following attempt to initialize Employee using designated initializers fails:
<code class="cpp">Employee e1{.name{"John"}, .surname{"Wick"}, .age{40}, .salary{50000}};</code>
This is because the C Standard specifies that designated initializers can only be used to initialize direct non-static data members of a class. In the above example, salary is a member of the derived class Employee, not the direct base class Person, so designated initialization is not allowed.
Instead, you must use traditional list initialization to initialize the inherited members:
<code class="cpp">Employee e1{ "John", "Wick", 40, 50000 };</code>
Or, as pointed out by a comment, you can use a nested designated initializer list to initialize the base class:
<code class="cpp">Employee e1{ { .name{"John"}, .surname{"Wick"}, .age{40} }, 50000 };</code>
In this case, the direct base class is initialized using a designated initializer list, while the Employee class as a whole is initialized using a regular initializer list.
The above is the detailed content of Can Designated Initializers be Used to Initialize Inherited Members in C 20 Aggregates?. For more information, please follow other related articles on the PHP Chinese website!