Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
Medicine Avatar asked Dec 26 '22 19:12

Medicine


2 Answers

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.

like image 160
Jesse Good Avatar answered Jan 17 '23 12:01

Jesse Good


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.

like image 25
Luchian Grigore Avatar answered Jan 17 '23 13:01

Luchian Grigore