I've got a question about one of the c++20 feature, designated initializers (more info about this feature here)
#include <iostream>
constexpr unsigned DEFAULT_SALARY {10000};
struct Person
{
std::string name{};
std::string surname{};
unsigned age{};
};
struct Employee : Person
{
unsigned salary{DEFAULT_SALARY};
};
int main()
{
std::cout << std::boolalpha << std::is_aggregate_v<Person> << '
'; // true is printed
std::cout << std::boolalpha << std::is_aggregate_v<Employee> << '
'; // true is printed
Person p{.name{"John"}, .surname{"Wick"}, .age{40}}; // it's ok
Employee e1{.name{"John"}, .surname{"Wick"}, .age{40}, .salary{50000}}; // doesn't compile, WHY ?
// For e2 compiler prints a warning "missing initializer for member 'Employee::<anonymous>' [-Wmissing-field-initializers]"
Employee e2 {.salary{55000}};
}
This code was compiled with gcc 9.2.0 and -Wall -Wextra -std=gnu++2a
flags.
As you can see above, both structs, Person
and Employee
are aggregates but initialization of Employee
aggregate isn't possible using designated initializers.
Could someone explain me why ?
See Question&Answers more detail:os