Data members are initialized in the order that they are declared in the class. Even if you use the constructor's member initialization list, data members are always initialized in declaration order, not in the order that you specify in the initialization list.
When you assign a default value to a data member, the compiler treats it as-if you had used that value in the constructor's member initialization list instead. In other words, your example code:
class A
{
public:
A ()
: var (5)
{}
int x = var;
...
private:
int var = 0;
};
Is treated as-if you had written it like this instead:
class A
{
public:
A ()
: x (var), var (5)
{}
int x;
...
private:
int var;
};
See the problem? x is declared before var, and so x is initialized before var, which is an error since var hasn't been initialized yet.
To fix that, you can either:
- move the declaration of
var above the declaration of x in the class:
class A
{
private:
int var = 5;
public:
A () = default;
int x = var;
...
};
Or, you can simply not use a default value for x, assign it explicitly in the constructor's body rather than its initialization list:
class A
{
public:
A ()
{
x = var;
}
int x;
...
private:
int var = 5;
};