Virtual Destructors in CPP

In this article, we will discuss virtual destructors in CPP.

Destructor is part of Resource Acquisition Is Initialization(RAII) programming idiom. The basic idea of RAII is constructor will acquire(allocate) resources and the destructor will release resources for a class. The most common example of a destructor is when the constructor uses new, and the destructor uses delete.

Destructors are also known as “prepare to die” member functions. They have often abbreviated “dtor”. Now let’s dive into virtual destructors.

When to use virtual destructors?

When we want to delete polymorphically we can use a virtual destructor. In other words, virtual destructors are useful when we want to delete an instance of a derived class through a pointer to the base class.

Let’s understand it with an example. Consider base class without destructor.

#include <iostream>

using namespace std;

class Base{
public:
     ~Base(){ cout<<"Base destructor"<<endl; }

};

class Derived : public Base{
public:
    ~Derived(){ cout<<"Derived destructor"<<endl; }
};

int main()
{
    Base *pBase=new Derived();
    delete pBase;
    return 0;
}

Output

Base destructor

Here only base class destructor called, derived class destructor not called and as a result resource will not be released( Here we are only printing for sake of simplicity). To solve this issue we can use a virtual destructor.

virtual ~Base(){ cout<<“Base destructor”<<endl; }

// Virtual destructor example

#include <iostream>

using namespace std;

class Base{
public:
    virtual ~Base(){ cout<<"Base destructor"<<endl; }

};
class Derived : public Base{
public:
    ~Derived(){ cout<<"Derived destructor"<<endl; }
};

int main()
{
    Base *pBase=new Derived();
    delete pBase;
    return 0;
}

Output

Derived destructor
Base destructor

From this, we can see first the derived class destructor is called the base class destructor.

Conclusion

In conclusion, a base class destructor should be virtual if we are going to delete polymorphically ( delete via a pointer to base).

Leave a Comment