Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make brace initialization and default values work together?

The following code works

class A
{
public:
    int i;
    float f;
};


int main()
{
    A a{ 1, 0.1 };
    return 0;
}

However, if I add default values for A's members, it doesn't work

class A
{
public:
    int i = 0;
    float f = 3.14;
};

How to make both work together?

like image 451
user1899020 Avatar asked Jun 23 '14 14:06

user1899020


1 Answers

You have to define a default and a custom constructor like the example below:

class A
{
public:
    A() {}  
    A(int const _i, float const _f) : i(_i), f(_f) {}
    int i = 0;
    float f = 3.14;
};

LIVE DEMO

However as already mentioned by @Kerek SB, @T.C. in the comments this will be fixed in C++14 and your code will work as is.

like image 187
101010 Avatar answered Sep 18 '22 13:09

101010