rsp rsp - 26 days ago 7
C++ Question

Order of member initializers

Following code gives correct output, If I declare variables

i
and
j
, Like
int i, j;


class A
{
int i, j;

public:
A(int val) : i(val), j(i + 1)
{
cout<<i<<endl<<j<<endl;
}
};


But If I declare variable
i
and
j
, like
int j, i;
. then
j
print garbage value.

class A
{
int j, i;

public:
A(int val) : i(val), j(i + 1)
{
cout<<i<<endl<<j<<endl;
}
};


So, Is it depend on order of declaration of variables?

Answer Source

Is it depend on order of declaration of variables?

Yes, the data members are always initialized in the order of their declarations, which has nothing to do with the order of the member initializer lists.

That means for your 2nd code snippet, j is always initialized before i; but when it's initialized by member initializer i is still not initialized.

The complete initialization order for the object is:

(emphasis mine)

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed