TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  OLC#018Checked automatically with code checker

Synopsis:Let the order of the initializer list be the same as the order of declaration in the header file: first base classes, then data members
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
}


Literature References:
ISC++ Rule 5.6