Question

I need to know when the constructors of basis classes are called in the call of a derived class constructor.

Small example:

class Base1
{...}

class Base2
{...}

class Derived : Base1,Base2
{...}

int main (int argc, char** argv)
{
Derived Child;
}

With the command Derived Child; the constructor of Derived is called, but I have read that before the Derived class constructor is executed all base constructors are executed, i.e. constructors of Base1 and Base2.

So I am wondering how the event order would be if the constructor of class Derived looked like this

Derived::Derived (Parameters)
:                      //initialization list
Base2 (Parameters)
{...}

Is the constructor of class Base2 now called in the initialazation list of constructor Derived or is it called before. Furthermore are all base class constructors called at the beginning of the call of constructor Derived or when the initialization list of class Derived constructor starts.

greetings streight

Was it helpful?

Solution

Order of call of constructors is 1st Base class then derived class.

In current example Order of call of constructors is as : Basis1 Basis2 Derived

If we change class definition to

class Derived : Basis2,Basis1

then order of constructor calls will be: Basis2 Basis1 Derived

Base class constructor are always called before derived class, whether called explicitly from initialization list or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top