Is the construction order of member variables of the class undefined in C ++?

Possible duplicate:
User fields, construction order

If I have a class with two members like this:

class A { int a; int b; A() {} }; 

Is the order in which a and b constructed undefined?

If I use cl , then no matter in what order I call the constructors, the members are always built in the order in which they are declared in the class. In this case, there will always be a , then b , even if I define the constructor for a as:

 A() : b(), a() {} 

But I assume that this is just the behavior of a particular compiler.

+4
source share
2 answers

No. Members are created in the order in which they are declared.

You are advised to arrange the initialization list in the same order, but is not required from you. It is just very confusing if you do not, and can lead to error detection.

Example:

 struct Foo { int a; int b; Foo() : b(4), a(b) { } // does not do what you think! }; 

This construct is actually undefined because you are reading an uninitialized variable in the a(b) initializer.


Standard link (C ++ 11, 12.6.2 / 10):

- Then direct base classes are initialized in the order of declaration, as they appear in the list of base qualifiers (regardless of the order of mem initializers).

- Then non-static data elements are initialized in the order in which they were declared in the class definition (again, regardless of the order of mem-initializers).

+13
source

The initialization order is the same as the declaration order in the class.

If the order in the constructor initialization list is different, then compilers usually give a warning. For example, for a class:

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

GCC will warn that:

 $ g++ -Wall c.cc c.cc:5: error: expected `:' before 'int' c.cc: In constructor 'A::A()': c.cc:6: warning: 'A::b' will be initialized after c.cc:5: warning: 'int A::a' c.cc:3: warning: when initialized here 

This is because it can easily lead to errors. In the above example, the value of a will be unspecified.

+2
source

Source: https://habr.com/ru/post/1432520/


All Articles