Brace-enclosed initializer list not possible with derived types?

I just started to use initializer lists in my code.

Correct me if I'm wrong but it seems not allowed to do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct MyBase
{
    int mInt;
};

struct MyDerived: MyBase
{
    float mFloat;
};

int main()
{
    MyDerived myderived = { {1}, 9.f };  //not this
    MyDerived another = { 2, 12.f };     //not this either
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct MyBase
{
    int mInt;

    MyBase(int n) : mInt(n) {}

};

struct MyDerived : MyBase
{
    float mFloat;

    MyDerived(int n, float f) : MyBase(n), mFloat(f) {}
};

int main()
{

    MyDerived myderived = { {1}, 9.f };
    MyDerived another = { 2, 12.f };     
    return 0;
}
Okay, so basically not without explicitly defining constructors. The reason I started using initializer lists was to avoid writing default constructors with simple data assignment (thread: http://www.cplusplus.com/forum/general/109091/ )
Last edited on
The reason I started using initializer lists was to avoid writing default constructors with simple data assignment


Can't really do that where inheritance is involved. You can, of course, specify that the default constructor is defaulted by the compiler, but that's more work than just writing an empty constructor.
According to the C++ Standard

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).

As your class MyDerived has a base class it is not an aggregate and can not be initialized such way as you try to use.i
Ok thanks for clearing that up.

How about when you are creating a temporary variable (maybe it's an R-value, I'm not so sure of the correct term but here is the example):

1
2
3
4
//some function being called somewhere
foo( MyClass( 3, 4 ) );    //normally I would do this with a constructor

foo( MyClass{ 3, 4 } );    //this seems to be invalid 
These code is valid if the compiler supports the list initialization.
Topic archived. No new replies allowed.