Search code examples
c++initializationc++14

C++ Call default constructor for Struct and its inherited members


I'd like to be able to initialize an object with the following syntax in C++14:

const auto data1 = DataOne{1, 2, 3};
const auto data2 = DataTwo{1, 2, 3, 4, 5};
const auto data3 = DataThree{1, 2, 3, 4, 5, 6, 7};

Which gives me the following error message:

error msg `error: no matching function for call to ‘DataThree::DataThree(<brace-enclosed initializer list>)’`

With the types defined as:

struct DataOne
{
    int a;
    int b;
    int c;
};

struct DataTwo : DataOne
{
    int d;
    int e;
};

struct DataThree : DataTwo
{
    int f;
    int g;
};

I dont want to use the struct in struct method because then I will need to call params through double or triple dots which I dont want to use because all the members are equal important and it will look bad to read.


Solution

  • As of C++17, the syntax you wish for is valid:

    const auto data3 = DataThree{1, 2, 3, 4, 5, 6, 7};
    

    Live demo

    Before that, aggregate initialization would be illegal per [dcl.init.aggr]/1:

    An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).