Constructors and Destructors in C++
Constructors and Destructors in C++
inheritance
Destructor
• a destructor is the last function that is going to be
called before an object is destroyed.
• A destructor works opposite to constructor;
• it destructs the objects of classes.
• It can be defined only once in a class.
• Like constructors, it is invoked automatically.
• A destructor is defined like constructor. It must
have same name as class. But it is prefixed with a
tilde sign (~).
• Constructors: Top- down approach
• Destructors: bottom up approach
Constructor and Destructor in Inheritance
Invocation of constructors and destructors depends on class derived:public base
the type of inheritance being implemented.
{
single inheritance public:
derived()
Base class constructors are called first and the derived
class constructors are called next in single inheritance. {
cout<<"derived class constructor"<<endl;
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 is called ~derived()
next. {
#include<iostream> cout<<"derived class destructor"<<endl;
using namespace std;
}
class base {
public: };
base() int main()
{ {
cout<<"base class constructor"<<endl;
}
derived d;
~base() return 0;
{ }
cout<<"base class destructor"<<endl;
}
};
Constructor and destructor in multiple inheritance
• Constructors from all base class are invoked first and the derived class constructor
is called.
• Order of constructor invocation depends on the order of how the base is 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.
#include<iostream> class derived:public base_one, public
using namespace std; base_two
class base_one {
{ public: public:
base_one() derived()
{ {
cout<<"base_one class constructor"<<endl; cout<<"derived class constructor"<<endl;
} }
~base_one() ~derived()
{ {
cout<<"base_one class destructor"<<endl; cout<<"derived class destructor"<<endl;
} }
}; };
class base_two { public: int main()
base_two() {
{ derived d;
cout<<"base_two class constructor"<<endl; return 0;
} }
~base_two()
{
cout<<"base_two class destructor"<<endl;
}
};