When we should use virtual destructor?

It is used whenever a base class pointer is pointing to its derived class. In such a case when a user tries to delete the base class pointer then it results in deallocating the memory occupied by the base class.Therefore instead the derived class getting destroyed the base class does. Now as the base class gets destroyed the base class pointer which was pointing to its derived class hold no meaning as it is already destroyed.

In such a case we should make the destructors of the base class virtual so that whenever a delete is called on the base class pointer then as the destructor is virtual the compiler will call the destructor of the respective derived class.Hence the  scenario wont be breached when a base class pointer points to derived class as it would help deleting the respective derived class object.

Example:

#include "iostream.h"
class base {
        public:
                base(){}
                virtual ~base(){
                        cout<<"Base destructor is called"<<endl;
                }
};
 
class derived : public base {
        public:
                derived(){}
                ~derived(){
                        cout<<"Derived destructor is called"<<endl;
                }
};
 
main()
{
        base *p1 = new derived;
        derived *p2 = new derived;
        delete p1;
        delete p2;
}

Output: without virtual destructor:

Base destructor is called
Derived destructor is called
Base destructor is called

Output: with virtual destructor:

Derived destructor is called
Base destructor is called
Derived destructor is called
Base destructor is called

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

4 thoughts on “When we should use virtual destructor?

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in