In C++, what’s a virtual destructor and when is it needed?

 

As you may know, in C++ a destructor is generally used to deallocate memory and do some other cleanup for a class object and it’s class members whenever an object is destroyed. Destructors are distinguished by the tilde, the ‘~’ that appears in front of the destructor name. In order to define a virtual destructor, all you have to do is simply add the keyword “virtual” before the tilde symbol.

The need for virtual destructors in C++ is best illustrated by some examples. Let’s start by going through an example that does not use virtual destructors, and then we will go through an example that does use virtual destructors. Once you see the difference, you will understand why virtual destructors are needed. Take a look at the code below to start out:




Example without a Virtual Destructor:

#include iostream.h
class Base
{
   	public:
      	Base(){ cout<<"Constructing Base";}
      	
     // this is a destructor:
	
	~Base(){ cout<<"Destroying Base";}
};

class Derive: public Base
{
        public:
       	Derive(){ cout<<"Constructing Derive";}
       	
       	~Derive(){ cout<<"Destroying Derive";}
 };

void main()
{
    	Base *basePtr = new Derive();
        
        delete basePtr;
}

The output after running the code above would be:

Constructing Base  
Constructing Derive 
Destroying Base

Based on the output above, we can see that the constructors get called in the appropriate order when we create the Derive class object pointer in the main function.

But there is a major problem with the code above: the destructor for the "Derive" class does not get called at all when we delete ‘basePtr’.

So, how can we fix this problem?

Well, what we can do is make the base class destructor virtual, and that will ensure that the destructor for any class that derives from Base (in our case, its the "Derive" class) will be called.

Subscribe to our newsletter for more free interview questions.

Example with a Virtual Destructor:

So, the only thing we will need to change is the destructor in the Base class and here’s what it will look like – note that we highlighted the part of the code where the virtual keyword has been added in red:

class Base
{
   	public:
      	Base(){ cout<<"Constructing Base";}

	// this is a virtual destructor:
	virtual ~Base(){ cout<<"Destroying Base";}
};

Now, with that change, the output after running the code above will be:

Constructing Base  
Constructing Derive 
Destroying Derive
Destroying Base

Note that the derived class destructor will be called before the base class.

So, now you’ve seen why we need virtual destructors and also how they work.

One important design paradigm of class design is that if a class has one or more virtual functions, then that class should also have a virtual destructor.


Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.



FOLLOW Varoon Sahgal, Author of ProgrammerInterviewon

  • harshal

    Base *basePtr = new Derive();
    In above line, why one has to use base class pointer to create derived class object?
    Why cant he use derived class pointer directly?
    Any particular example or application, can you give?

    • sabee

      Incase if you virtual functions in your class, and through base pointer you need to access derived class virtual function then, you can use like this.

    • pip010

      this is the principle way of achieving runtime polymorphism in OOP C++.
      example: IDriver is pure abstract class, e.g.
      class IDriver
      {
      virtual void Init() = 0;
      };

      class USBDriver : public IDriver
      {
      virtual ~USBDriver(){}

      void Init(){}
      };

      IDriver* driver = nullptr;
      //runtime you decide that you need the USB not lets say another //RS232Driver

      driver = new USBDriver();

      delete driver;