c++inheritancestructaggregate-initializationaggregate-type

Why isn't a struct, empty other than inheriting an aggregate struct, aggregate-initializable?


Consider the following code:

struct A {
    int x;
    double y;
};

struct B : public A {};

int main() {
    A a {1, 2.3}; // (*)
    B b {1, 2.3}; // (**)
}

Line (*) compiles, line (**) doesn't.

Is this because B is not considered an "aggregate type"? If so, why isn't it? If not, what's the reason it can't be constructed this way?


Solution

  • GCC 10's default language version is C++14. In C++14 and prior, no aggregate could have any base classes.

    The reason? No good reason. So, from C++17, this rule was relaxed; now no aggregate can have no virtual, private, or protected base classes … but others are fine.

    Your code works in C++17. Add -std=c++17 to your compilation command.


    These rules had previously been modified for C++14; be sure to specify which language versions you're interested in when asking a question.