RAD Studio |  |

Order Of Calling Constructors
See Also
Collapse All

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,

Copy Code

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

the constructors are called in this order:

Copy Code

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

For the case of multiple base classes,

Copy Code

    class X : public Y, public Z
    X one;

the constructors are called in the order of declaration:

Copy Code

    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:

Copy Code

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

produces this order:

Copy Code

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

Or, for a more complicated example:

Copy Code

    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:

Copy Code

    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

Class Initialization

Invoking Destructors

Atexit

Exit And Destructors

abort And Destructors

Virtual Destructors

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!