Synopsis: | Let the order of the initializer list be: first base class constructor(s), then data members in the same order of declaration as in the header file |
Language: | C++ |
Severity Level: | 1 |
Category: | Object Life Cycle |
Description: |
The order in the initializer list is irrelevant to the execution order of the initializers. Putting initializers for data members and base classes in any other order than their actual initialization order is therefore highly confusing and error-prone. A data member could be accessed before it is initialized if the order in the initializer list is incorrect, see Example1. Virtual base classes are always initialized first. Then base classes, data members and finally the constructor body for the most derived class is run, see Example2. Example1: class Foo { public: Foo(int a, int b) : A(a), B(b), C(A * B) { } // C is initialized before B which at that moment still undefined! private: int A; int C; //C initialization depends on A and B and therefore should be declared after A and B. int B; }; Example2: class Derived : public Base // Base is number 1 { public: explicit Derived(int i); Derived(); private: int jM; // jM is number 2 Base bM; // bM is number 3 }; Derived::Derived(int i) : Base(i), jM(i), bM(i) // Recommended order 1 2 3 { // Empty } |