0
0
CppConceptBeginner · 3 min read

When to Use Virtual Destructor in C++: Explanation and Example

Use a virtual destructor in C++ when you have a base class with virtual functions and you expect to delete derived class objects through a base class pointer. This ensures the derived class's destructor runs correctly, preventing resource leaks and undefined behavior.
⚙️

How It Works

In C++, when you delete an object through a pointer to a base class, the destructor that runs depends on whether the base class destructor is virtual or not. If the destructor is not virtual, only the base class destructor runs, and the derived class destructor is skipped. This can cause resource leaks or incomplete cleanup.

Think of it like a cleanup crew: if you only call the base crew, the special tasks done by the derived crew won't be handled. Making the destructor virtual tells C++ to check the actual object type at runtime and call the correct destructor chain, cleaning up everything properly.

💻

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() { std::cout << "Derived destructor called\n"; }
};

int main() {
    Base* obj = new Derived();
    delete obj;  // Both destructors run 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 from and where objects might be deleted through a base class pointer. This is common in polymorphic designs where you handle objects via base pointers but the actual objects are derived types.

For example, in a graphics program, you might have a base class Shape and derived classes like Circle and Rectangle. If you store pointers to Shape but create derived objects, deleting them through Shape* requires a virtual destructor to clean up properly.

Key Points

  • Virtual destructors ensure the full destructor chain runs in polymorphic classes.
  • Always declare destructors virtual in base classes with virtual functions.
  • Not using virtual destructors can cause resource leaks and undefined behavior.
  • If a class is not meant to be a base class, a virtual destructor is not needed.

Key Takeaways

Declare destructors virtual in base classes used polymorphically to ensure proper cleanup.
Deleting derived objects through base pointers without virtual destructors causes incomplete destruction.
Virtual destructors enable safe and correct resource management in inheritance hierarchies.