Virtual Destructor in C++
A destructor in C++ is a member function of a class used to free the space occupied by or delete an object of the class that goes out of scope.
A destructor has the same name as the name of the constructor function in a class, but the destructor uses a tilde (~) sign before its function name.
Why we use virtual destructor in C++?
When an object in the class goes out of scope or the execution of the main() function is about to end, a destructor is automatically called into the program. The destructor() function executes in reverse order of the creation of the objects.
We have a situation:
When a pointer object of the base class is deleted that points to the derived class, only the parent class destructor is called due to the early bind by the compiler. In this way, it skips calling the derived class’ destructor, which leads to memory leaks issue in the program.
To ensure that the proper sequence of execution is following we have to declare the base class destructor as virtual.
When we use a virtual keyword preceded by the destructor tilde (~) sign inside the base class, it guarantees that first the derived class’ destructor is called. Then the base class’ destructor is called to release the space occupied by both destructors in the inheritance class.
Example:
Program to display execution of destructor function without using a virtual destructor in C ++.
#include<iostream> using namespace std; class base { public: base() { cout<<"Base class Constructor Function"<<endl; } ~base() { cout<<"Base class Destructor Function"<<endl; } }; class derived: public base { public: derived() { cout<<"Derived class Constructor Function"<<endl; } ~derived() { cout<<"Derived class Destructor Function"<<endl; } }; int main() { base *p=new derived; // Create a base class pointer object delete p; }
Output:
Base class Constructor Function
Derived class Constructor Function
Base class Destructor Function
Example:
Program to display execution of destructor function using a virtual destructor in C ++.
#include<iostream> using namespace std; class base { public: base() { cout<<"Base class Constructor Function"<<endl; } virtual ~base() { cout<<"Base class Destructor Function"<<endl; } }; class derived: public base { public: derived() { cout<<"Derived class Constructor Function"<<endl; } ~derived() { cout<<"Derived class Destructor Function"<<endl; } }; int main() { base *p=new derived; // Create a base class pointer object delete p; }
Output:
Base class Constructor Function
Derived class Constructor Function
Derived class Destructor Function
Base class Destructor Function