When to Use Virtual Destructor in C++: Explanation and Example
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
#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; }
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.