Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does initialization list work for base classes?

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;
}
like image 212
user1899020 Avatar asked Jun 23 '14 17:06

user1899020


2 Answers

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;
}
like image 78
quantdev Avatar answered Oct 22 '22 17:10

quantdev


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 };
like image 40
Vlad from Moscow Avatar answered Oct 22 '22 19:10

Vlad from Moscow