C++ Constructors


Let us consider an exmaple:
1. Multilevel Inheritance – Order of Constructor invocation
class A
{
public:
A()
{
cout<<“Constructor of base class Invoked “;
}
}
class B: public A
{
public:
B()
{
cout<<“Constructor of derived class Invoked “;
}
}
main()
{
B objB;
}

The questions is wether the constructor of base class will be invoked first or derived class first?
Obviously the base class parameters has to be arranged and organised first, so the base class constructor will be invoked before invoking the constructor of derived class.

2. Mulitple constructors in base class and derived class
class A
{
public:
A()
{
cout<<“Constructor of base class Invoked “;
}
A(int x)
{
cout<<“Argument Constructor of base class Invoked “;
}
}
class B: public A
{
public:
B()
{
cout<<“Constructor of derived class Invoked “;
}
B(int x)
{
cout<<“Argument Constructor of derived class Invoked “;
}
}
main()
{
B objB(5);
}
In this case our questions is , wether the argument constructor of base class will be invoked or not. It has to be understood that the argument constructor of base class is not invoked if it is not explicitly specified as:
B(int x):A(x)
{
cout<<“Argument Constructor of derived class Invoked “;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s