C ++ data element initialization order when using initialization list

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

According to standard data elements, C ++ are created and initialized in the order in which they are declared, right?

But when using the initialization list, we change the order of the data members, now they are initialized in the order of the initialization list or the declaration order?

+4
source share
5 answers

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

+7
source

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

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

Some compilers even warn you if the order is different.

+1
source

They are initialized in the order of declaration. Also, many compilers warn you that your initialization list does not match the declaration order, even though the standard allows it.

+1
source

In C ++ 11, you can also:

 class A { private: int a = 1; int b = 2; int c = 3; public: A() { // your code } }; 
+1
source
Class Data Elements

their declarations inside the class are always initialized in the upper> lower order and destroyed in the reverse order. The initialization list does not affect the initialization order of data items.

You can check the corresponding question below, as well as for more complex situations when using initialization lists,

How a function call works for an element of an elementized data object in the constructor initiator list

0
source

All Articles