Medicine
Medicine

Reputation: 2023

c++ data members initialization order when using initialization list

class A
{
private:
int a; 
int b; 
int c;

public:
A() : b(2), a(1), c (3)
{
}
};

As per C++ standard data members are constructed and initialized in the order they are declared, correct?

But when using initalization list, we are changing the order of data members, now do they initialize in order of initialization list or the order of declaration?

Upvotes: 4

Views: 2716

Answers (5)

Pravar Jawalekar
Pravar Jawalekar

Reputation: 605

class data members are always initialized in top->bottom order of their declaration inside class and destructed in reverse order. Initialization list doesn't affects the order of initialization of data members.

You can check below related question as well for more tricky situations while using initialization lists,

How function call is working on an unitialized data member object in constructor's initilalizer list

Upvotes: 0

Lucas Lima
Lucas Lima

Reputation: 1487

In C++11 you can also do:

class A
{
    private:
    int a = 1; 
    int b = 2; 
    int c = 3; 

public:
    A()
    {
       // your code
    }
};

Upvotes: 1

Öö Tiib
Öö Tiib

Reputation: 10979

They initialize in order of declaration. Also lot of compilers warn you that your initialization list does not match with declaration order, despite standard allows it.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258548

No, the initialization list has nothing to do with it.

Members are always initialized in the order in which they appear in the class body.

Some compilers will even warn you if the orders are different.

Upvotes: 1

Jesse Good
Jesse Good

Reputation: 52365

In the order of declaration, the order in the initialization list does not matter. Some compilers will actually give you warning (gcc) telling you that the initialization list order is different than the order of declaration. This is why you also have to be careful when you would use members to initialize other members, etc.

Upvotes: 7

Related Questions