2.8 Constructor and Destructor in Derived Class.pdf
1. Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423 603
(An Autonomous Institute, Affiliated to Savitribai Phule Pune University, Pune)
NAAC ‘A’Grade Accredited, ISO 9001:2015 Certified
Department of Computer Engineering
(NBA Accredited)
Subject- Object Oriented Programming (CO212)
Unit 2 – Overloading and Inheritance
Topic – 2.8 Constructor and Destructor in Inheritance
Prof. V.N.Nirgude
Assistant Professor
E-mail :
nirgudevikascomp@sanjivani.org.i
Contact No: 9975240215
2. Constructor and Destructor in Inheritance
DEPARTMENT OF COMPUTER ENGINEERING , SCOE,KOPARGAON 2
• Invocation of constructors and destructors depends on the type of inheritance
being implemented.
Constructor and destructor in single inheritance:
• Base class constructors are called first and the derived class constructors are
called next in single inheritance.
• Destructor is called in reverse sequence of constructor invocation i.e. The
destructor of the derived class is called first and the destructor of the base class is
called next.
3. class base derived() Output :
{ { base class constructor
public: cout<<"derived class constructor"; derived class constructor
base() } derived class destructor
{ ~derived() base class destructor
cout<<"base class constructor"; {
} cout<<"derived class destructor";
~base() }
{
cout<<"base class destructor"; };
} int main()
}; {
class derived: public base derived d;
{
public:
}
Example of Constructor and Destructor in Single Inheritance
DEPARTMENT OF COMPUTER ENGINEERING , SCOE,KOPARGAON 3
4. Constructor and destructor in multiple inheritance
DEPARTMENT OF COMPUTER ENGINEERING , SCOE,KOPARGAON 4
• Constructors from all base classes are invoked first and then derived
class constructor is called.
• Order of constructor invocation depends on the order of how base
classess are inherited.
• For example:
• class D:public B, public C { //… }
• Here, B is inherited first, so the constructor of class B is called first
and then constructor of class C is called next.
• However, the destructor of derived class is called first and then
destructor of the base class which is mentioned in the derived class
declaration is called from last towards first in sequentially.
5. Example of constructor and destructor in multiple inheritance
class base_one
{
public:
base_one()
{
cout<<"base_one class constructor";
}
~base_one()
{
cout<<"base_one class destructor";
}
};
class base_two
{
public:
base_two()
{
cout<<"base_two class constructor";
}
~base_two()
{
cout<<"base_two class destructor";
}
};
class derived: public base_one, public
base_two
{
public:
derived()
{
cout<<"derived class constructor";
}
~derived()
{
cout<<"derived class destructor";
}
};
int main()
{
derived d;
return 0;
}
Output :
DEPARTMENT OF COMPUTER ENGINEERING , SCOE,KOPARGAON 5