Inheritance
and constructors and destructors
When
an object of the derived class is created ,the compiler first call the base
class constructor and then the constructor of the derived class. This because
the derived class is built up on the members of the base class. When the object
of a derived class expires first the derived class destructor is invoked
followed by the base class destructor.
#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<"\nConstructor of base class...";
}
~base()
{
cout<<"\nDestructor of base class.... ";
}
};
class derived:public base
{
public :
derived()
{
cout << "\nConstructor of derived ...";
}
~derived()
{
cout << "\nDestructor of derived ...";
}
};
class derived1 :public derived
{
public :
derived1()
{
cout << "\nConstructor of derived1 ...";
}
~derived1()
{
cout << "\nDestructor of derived1 ...";
}
};
int main()
{
derived1 x;
return 0;
}
Constructor of base class...
Constructor of derived ...
Constructor of derived1 ...
Destructor of derived1 ...
Destructor of derived ...
Destructor of base class....
The constructors are executed in the order of inherited class i.e.,
from base constructor to derived. Thedestructors are executed in the reverse
order.
•
Base class constructors are executed first ,before the derived class
constructors execution
•
Derived class can not inherit the base class constructor but it can call the
base class constructor by using
•
Base_class name::base_class_constructor() in derived class definition
•
If there are multiple base classes ,then its start executing from the left most
base class
•
In multilevel inheritance, the constructors will be executed in the order of
inheritance.
size of derived class object=size of all base class data members
+ size of all data members in derived class.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.