Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializer list with struct and inheritance [duplicate]

I'm using initializer lists for structs. But, it doesn't work with inheritance.

This code is good.

struct K {
int x, y;
};

K k {1, 2};

But, this produces an error.

struct L : public K {};
L l {1, 2};

Also, this does not work.

struct X {
    int x;
};

struct Y : public X {
    int y;
};

Y y {1, 2};

Is there a way to use initializer lists with inherited structs. I'm using them in templates and so it doesn't compile if it is an inherited class or not.

like image 749
Mochan Avatar asked Aug 11 '26 17:08

Mochan


1 Answers

Your code would work with C++17. Since C++17 both L and Y are considered as aggregate type:

no virtual, private, or protected (since C++17) base classes

Then brace elision is allowed; i.e. the braces around nested initializer lists for subaggregate could be elided and then you can just write L l {1, 2}; and Y y {1, 2}; (instead of L l {{1, 2}}; and Y y {{1}, 2};).

If the aggregate initialization uses copy- (until C++14)list-initialization syntax (T a = {args..} or T a {args..} (since C++14)), the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

LIVE

Before C++17 it doesn't work because list initialization is performed instead, the appropriate constructors are tried to be used and fails.

like image 182
songyuanyao Avatar answered Aug 14 '26 10:08

songyuanyao



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!