Rule A8-5-1 (required, implementation, automated)
In an initialization list, the order of initialization shall be following: (1) virtual base classes in depth and left to right order of the inheritance graph, (2) direct base classes in left to right order of inheritance list, (3) non-static data members in the order they were declared in the class definition.
Rationale
To avoid confusion and possible use of uninitialized data members, it is recommended that the initialization list matches the actual initialization order. Regardless of the order of member initializers in a initialization list, the order of initialization is always: Virtual base classes in depth and left to right order of the inheritance graph. Direct non-virtual base classes in left to right order of inheritance list.
Non-static member data in order of declaration in the class definition. Note that “The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.” [C++14 Language Standard [3]]
Example
// $Id: A8-5-1.cpp 271696 2017-03-23 09:23:09Z piotr.tanski $
#include <cstdint>
#include <string>
class A
{
};
class B
{
};
class C : public virtual B, public A
{
public:
C() : B(), A(), s() {} // Compliant
// C() : A(), B() { } // Non-compliant - incorrect order of initialization
private:
std::string s;
};
class D
{
};
class E
{
};
class F : public virtual A, public B, public virtual D, public E
{
public:
F() : A(), D(), B(), E(), number1(0), number2(0U) {} // Compliant
F(F const& oth)
: B(), E(), A(), D(), number1(oth.number1), number2(oth.number2)
{
} // Non-compliant - incorrect
// order of initialization
private:
std::int32_t number1;
std::uint8_t number2;
};
See also
HIC++ v4.0 [9]:12.4.4 Write members in an initialization list in the order in which they are declared