Construction order of derived class objects (C++ only)

When a derived class object is created using constructors, it is created in the following order:

  1. Virtual base classes are initialized, in the order they appear in the base list.
  2. Nonvirtual base classes are initialized, in declaration order.
  3. Class members are initialized in declaration order (regardless of their order in the initialization list).
  4. The body of the constructor is executed.

The following example demonstrates this:

#include <iostream>
using namespace std;
struct V {
  V() { cout << "V()" << endl; }
};
struct V2 {
  V2() { cout << "V2()" << endl; }
};
struct A {
  A() { cout << "A()" << endl; }
};
struct B : virtual V {
  B() { cout << "B()" << endl; }
};
struct C : B, virtual V2 {
  C() { cout << "C()" << endl; }
};
struct D : C, virtual V {
  A obj_A;
  D() { cout << "D()" << endl; }
};
int main() {
  D c;
}

The following is the output of the above example:

V()
V2()
B()
C()
A()
D()

The above output lists the order in which the C++ run time calls the constructors to create an object of type D.

Related information