Why a Virtual Destructor is Needed in C++
In C++, when you have a base class pointer pointing to a derived class object, deleting through the base pointer can cause problems if the base class destructor is not virtual.
Example
struct Base {
// No virtual destructor
};
struct Derived : public Base {
int* data;
~Derived() {
delete data; // clean up allocated memory
}
};
Base* obj = new Derived();
delete obj; // Problem! Only Base destructor is called
In this example, the Derived destructor is never called because the destructor in Base is not virtual.
As a result, any resources allocated by Derived (like data) are not freed,
causing a memory leak.
Solution: Virtual Destructor
struct Base {
virtual ~Base() = default; // Virtual destructor ensures proper cleanup
};
struct Derived : public Base {
int* data;
~Derived() {
delete data;
}
};
Base* obj = new Derived();
delete obj; // Correct! Derived destructor is called first, then Base destructor
By marking the base class destructor as virtual:
- C++ creates a vtable that stores the actual destructor to call.
- Deleting a derived object through a base pointer will call the derived destructor first, then the base destructor.
- All resources in the derived class are properly cleaned up, avoiding memory leaks.
Rule of Thumb
If a class has any virtual functions and is intended to be used polymorphically (deleted through a base pointer), its destructor should always be virtual.