Home  >  Article  >  Backend Development  >  Can Designated Initializers be Used to Initialize Base Class Members in C 20?

Can Designated Initializers be Used to Initialize Base Class Members in C 20?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 19:06:30640browse

 Can Designated Initializers be Used to Initialize Base Class Members in C  20?

Designated Initializers in C 20: Limitations Explained

Designated initializers introduced in C 20 allow you to explicitly specify the order of member initialization for aggregates. However, a recent question has arisen regarding their use for derived classes.

In the code example provided:

<code class="cpp">struct Person
{
    std::string name{};
    std::string surname{};
    unsigned age{};
};

struct Employee : Person
{
    unsigned salary{DEFAULT_SALARY};
};

int main()
{
    Employee e1{.name{"John"}, .surname{"Wick"}, .age{40}, .salary{50000}}; // doesn't compile
    Employee e2 {.salary{55000}}; // warning: missing initializer for base class member
}</code>

The code fails to compile e1 because designated initializers can only be used to initialize non-static members of the derived class directly. In other words, you cannot initialize members of a base class directly with designated initializers.

To resolve this, you can use the following approaches:

  • Traditional list initialization:

    <code class="cpp">Employee e1{ "John", "Wick", 40, 50000 };</code>
  • Nested designated initializer list:

    <code class="cpp">Employee e1{ { .name{"John"}, .surname{"Wick"}, .age{40} }, 50000 };</code>

Alternatively, as suggested by @Jarod42, you can also specify the initializer list for the base class explicitly:

<code class="cpp">Employee e1{ { .name{"John"}, .surname{"Wick"}, .age{40} }, .salary{50000} };</code>

This allows you to initialize both the direct base class members and the derived class members using designated initializers.

The above is the detailed content of Can Designated Initializers be Used to Initialize Base Class Members in C 20?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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