Virtual Destructors in C++
A virtual destructor however, is pretty much feasible in C++. in fact, its use is often promoted in certain situations. One such situation is when we need to make sure that the different destructors in an inheritance hierarchy are called in order, particularly, when the base class pointer is reffering to a derived type object. it must be noted here that the order of calling of destructors in an inheritance hierarchy is opposite to that of constructors.
-> Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of the Base class must be made virtual for proper destrucstion of the object when the program exits.
NOTE: Constructors are never Virtual, only Destructors can be Virtual.
// C++ program on virtual destructor
A virtual destructor however, is pretty much feasible in C++. in fact, its use is often promoted in certain situations. One such situation is when we need to make sure that the different destructors in an inheritance hierarchy are called in order, particularly, when the base class pointer is reffering to a derived type object. it must be noted here that the order of calling of destructors in an inheritance hierarchy is opposite to that of constructors.
-> Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of the Base class must be made virtual for proper destrucstion of the object when the program exits.
NOTE: Constructors are never Virtual, only Destructors can be Virtual.
// C++ program on virtual destructor
#include<iostream>
using namespace std;
class Base
{
public:
virtual ~Base()
{
cout << "Base Destructor\n";
}
};
class Derived:public Base
{
public:
~Derived()
{
cout<< "Derived Destructor"<<endl;
}
};
int main()
{
Base* b = new Derived; // Upcasting
delete b;
return 0;
}
using namespace std;
class Base
{
public:
virtual ~Base()
{
cout << "Base Destructor\n";
}
};
class Derived:public Base
{
public:
~Derived()
{
cout<< "Derived Destructor"<<endl;
}
};
int main()
{
Base* b = new Derived; // Upcasting
delete b;
return 0;
}
OUTPUT:
Derived Destructor
Base Destructor
-> When we have Virtual destructor inside the base class, then first Derived class destructor is called and then Base class destructor is called, which is the desired behaviour.Derived Destructor
Base Destructor