Home > Backend Development > C++ > Can Designated Initializers be Used to Initialize Inherited Members in C 20 Aggregates?

Can Designated Initializers be Used to Initialize Inherited Members in C 20 Aggregates?

Patricia Arquette
Release: 2024-10-29 02:44:02
Original
473 people have browsed it

Can Designated Initializers be Used to Initialize Inherited Members in C  20 Aggregates?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template