Order of Constructor Call with Inheritance in C++
Base
class constructors are always called in the derived class constructors.
Whenever you create derived class object, first the base class default
constructor is executed and then the derived class's constructor finishes
execution.
Whether derived class's default constructor is called or
parameterised is called, base class's default constructor is always called
inside them.To call base class's parameterised constructor inside derived
class's parameterised constructor, we must mention it explicitly while
declaring derived class's parameterized constructor.
Fig: Order of Constructor Call with Inheritance in C++ |
Program:
#include<iostream.h>’
#include<conio.h>
class Base
{
int x;
public:
Base()
{
cout<<”base default constructor”;
}
};
class Derived: public Base
{
int y;
public:
Derived()
{
cout<<”derived
default constructor”;
}
Derived(int i)
{
cout<<”derived
parameterized constructor”;
}
};
void main()
{
Base b;
Derived d1;
Derived d2(10);
getch();
}
Output:
Base default
constructor
Base default constructor
Derived default
constructor
Base default
constructor
Derived parameterized
constructor
No comments:
Post a Comment