Order Of Calling Constructors

From Appmethod Topics
Jump to: navigation, search

Go Up to Constructors Index

In the case where a class has one or more base classes, the base class constructors are invoked before the derived class constructor. The base class constructors are called in the order they are declared.

For example, in this setup,

class Y {...}
class X : public Y {...}
X one;

the constructors are called in this order:

Y();   // base class constructor
X();   // derived class constructor

For the case of multiple base classes,

class X : public Y, public Z
X one;

the constructors are called in the order of declaration:

Y();  // base class constructors come first
Z();
X();

Constructors for virtual base classes are invoked before any nonvirtual base classes. If the hierarchy contains multiple virtual base classes, the virtual base class constructors are invoked in the order in which they were declared. Any nonvirtual bases are then constructed before the derived class constructor is called.

If a virtual class is derived from a nonvirtual base, that nonvirtual base will be first so that the virtual base class can be properly constructed. The code:

class X : public Y, virtual public Z
X one;

produces this order:

Z();   // virtual base class initialization
Y();   // nonvirtual base class
X();   // derived class

Or, for a more complicated example:

class base;
class base2;
class level1 : public base2, virtual public base;
class level2 : public base2, virtual public base;
class toplevel : public level1, virtual public level2;
toplevel view;

The construction order of view would be as follows:

base();      // virtual base class highest in hierarchy
             // base is constructed only once
base2();     // nonvirtual base of virtual base level2
             // must be called to construct level2
level2();    // virtual base class
base2();     // nonvirtual base of level1
level1();    // other nonvirtual base
toplevel();

If a class hierarchy contains multiple instances of a virtual base class, that base class is constructed only once. If, however, there exist both virtual and nonvirtual instances of the base class, the class constructor is invoked a single time for all virtual instances and then once for each nonvirtual occurrence of the base class.

Constructors for elements of an array are called in increasing order of the subscript.

See Also