Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does inheriting constructors break aggregate initialization? [duplicate]

Tags:

c++

Why does inheriting constructors from a base class break aggregate initialization?

For example, this works:

struct MyArray : std::array<int, 2ul> {};

MyArray a{1, 2};

but this doesn't work:

struct MyArray : std::array<int, 2ul>
{
     using std::array<int, 2ul>::array;
};

MyArray a{1, 2};
like image 597
rnorthcott Avatar asked Feb 07 '26 07:02

rnorthcott


1 Answers

Since C++17, aggregates can have base classes, so that for such structures being derived from other classes/structures list initialization is allowed:

struct MoreData : Data {
    bool done;
};

MoreData y{{"test1", 6.778}, false};

In C++17 an aggregate is defined as

  • either an array
  • or a class type (class, struct, or union) with:
    • no user-declared or explicit constructor
    • no constructor inherited by a using declaration
    • no private or protected non-static data members
    • no virtual functions
    • no virtual, private, or protected base classes

For more details you can refer to Chapter 4 Aggregate Extensions from C++17 - The Complete Guide By Nicolai M. Josuttis

like image 183
DailyLearner Avatar answered Feb 09 '26 02:02

DailyLearner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!