Constructors execution order of class objects (C++ only)

When a class object is created using constructors, the execution order of constructors is:

  1. Constructors of Virtual base classes are executed, in the order that they appear in the base list.
  2. Constructors of nonvirtual base classes are executed, in the declaration order.
  3. Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
  4. The body of the constructor is executed.
The following example demonstrates these:
#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.

C++0x
In the class body, if the delegating process exists, user code segments in the delegating constructors are executed after the completion of the target constructor. The inner most delegating constructor is executed first, then the next enclosing delegating constructor, until the outer most enclosing delegating constructor is executed.

Example:
#include <cstdio>
using std::printf;

class X{
public:
    int i,j;
    X();
    X(int x);
    X(int x, int y);
    ~X();
}

X::X(int x):i(x),j(23) {printf("X:X(int)\n");}
X::X(int x, int y): X(x+y) { printf("X::X(int,int)\n");}
X::X():X(44,11) {printf("X:X()\n");}
X::~X() {printf("X::~X()\n");}

int main(void){
  X x;
}
The output of the example is:
X::X(int)
X::X(int,int)
X:X()
X::~X()

For more information, see Delegating constructors (C++0x)

C++0x