0
0
CppConceptBeginner · 3 min read

What is Virtual Destructor in C++ and Why Use It?

A virtual destructor in C++ is a destructor declared with the virtual keyword to ensure that when deleting an object through a base class pointer, the derived class's destructor is called properly. This prevents resource leaks by allowing the full cleanup of derived objects.
⚙️

How It Works

Imagine you have a toolbox (base class) and inside it, you keep different tools (derived classes). When you want to throw away a tool, you need to make sure you clean up all parts of it, not just the toolbox. In C++, if you delete an object through a pointer to the base class, only the base class destructor runs by default, which can leave parts of the derived tool uncleaned.

Declaring the destructor as virtual tells C++ to check the actual type of the object at runtime and call the correct destructor for the derived class first, then the base class destructor. This is like telling the toolbox to open and let the specific tool clean itself properly before throwing it away.

💻

Example

This example shows a base class pointer deleting a derived class object. Without a virtual destructor, the derived destructor won't run, causing incomplete cleanup.

cpp
#include <iostream>

class Base {
public:
    virtual ~Base() { std::cout << "Base destructor called\n"; }
};

class Derived : public Base {
public:
    ~Derived() override { std::cout << "Derived destructor called\n"; }
};

int main() {
    Base* obj = new Derived();
    delete obj; // Calls Derived and Base destructors because Base destructor is virtual
    return 0;
}
Output
Derived destructor called Base destructor called
🎯

When to Use

Use a virtual destructor in any base class that is meant to be inherited and where objects might be deleted through a base class pointer. This is common in polymorphism, where you handle different derived objects via base pointers.

For example, in a graphics program, you might have a base class Shape and derived classes like Circle and Rectangle. If you store shapes in a list of Shape* and delete them later, a virtual destructor ensures each shape cleans up its own resources properly.

Key Points

  • A virtual destructor ensures the correct destructor runs for derived objects.
  • It prevents resource leaks when deleting through base class pointers.
  • Always declare destructors virtual in polymorphic base classes.
  • If a base class destructor is not virtual, deleting derived objects via base pointers causes undefined behavior.

Key Takeaways

Declare destructors virtual in base classes used polymorphically to ensure proper cleanup.
Virtual destructors call derived class destructors first, then base class destructors.
Not using virtual destructors can cause resource leaks and undefined behavior.
Use virtual destructors whenever you expect to delete derived objects through base pointers.