Brace-enclosed initializer list not possible with derived types?

Aug 29, 2013 at 5:25am
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;
}
Aug 29, 2013 at 5:31am
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;
}
Aug 29, 2013 at 5:45am
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 Aug 29, 2013 at 5:46am
Aug 29, 2013 at 5:56am
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.
Aug 29, 2013 at 7:22am
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
Aug 29, 2013 at 7:56am
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 
Aug 29, 2013 at 8:07am
These code is valid if the compiler supports the list initialization.
Topic archived. No new replies allowed.