Does initialization list work for base classes? If so, how? For example
struct A
{
int i;
};
struct B : public A
{
double d;
};
int main()
{
B b{ A(10), 3.4 };
return 0;
}
Section § 8.5.1 of the standard defines an aggregate :
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
Since B
has a base class, is not an aggregate : you cannot use aggregate brace-initialization here.
EDIT :
You could however provide a constructor to make brace-initialization work (but it is still not an aggregate initialization) :
struct A
{
int i;
};
struct B : public A
{
B(int i, double d) : A {i}, d(d) {}
double d;
};
int main()
{
B b { 10, 3.6 };
return 0;
}
Structure B is not an aggregate type. So you may not use a braced-init list such a way.
However if you would define a constructor in class B then you could write for example
struct A
{
int i;
};
struct B : public A
{
B( int x, double d ) : A { x }, d( d ) {}
double d;
};
B b { 1, 2.0 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With