Virtual Destructors in C++: Safe Cleanup Through Base-Class Pointers
What is Virtual Destructors in C++: Safe Cleanup Through Base-Class Pointers? When deleting a dynamically allocated derived class object through a pointer to its base class, if the base class destructor is not virtual, only the base destr...
Why is a virtual destructor mandatory when deleting derived objects through a base-class pointer?
Explanation & In-Depth Details
```text
Base* ptr = new Derived();
delete ptr;
NON-VIRTUAL DESTRUCTOR:
Calls Base::~Base() ONLY ──► Derived members & memory leaked! (UB)
VIRTUAL DESTRUCTOR:
Calls Derived::~Derived() ──► Calls Base::~Base() ──► 100% Clean!
```
2. Standard Guideline:
A base class destructor should be either `public virtual` (for polymorphic deletion) or `protected non-virtual` (if polymorphism is not used for deletion).
Code Example
#include <iostream>
#include <memory>
class SafeBase {
public:
SafeBase() { std::cout << "SafeBase allocated.\n"; }
// Virtual destructor guarantees full derived destruction
virtual ~SafeBase() { std::cout << "SafeBase destroyed.\n"; }
};
class HeavyDerived : public SafeBase {
private:
int* largeBuffer;
public:
HeavyDerived() : largeBuffer(new int[1000]) {
std::cout << "HeavyDerived allocated 4000 bytes on heap.\n";
}
~HeavyDerived() override {
delete[] largeBuffer;
std::cout << "HeavyDerived freed heap memory safely.\n";
}
};
int main() {
std::cout << "--- Polymorphic Deletion via Base Pointer ---\n";
SafeBase* polyPtr = new HeavyDerived();
delete polyPtr; // Triggers HeavyDerived dtor first, then SafeBase dtor
std::cout << "--- Deletion Complete ---\n";
return 0;
}Interview Question & Tips
A: Compilers emit `-Wnon-virtual-dtor`, warning that deleting an object through a pointer to this base class will cause undefined behavior.
Q: When is it acceptable for a base class to have a non-virtual destructor?
A: When the class is not intended to be used polymorphically for dynamic deletion, and its destructor is declared `protected` to prevent direct `delete` on base pointers.
Best Practices
• Use `= default` for virtual destructors when no custom cleanup logic is required.
• Use smart pointers (`std::unique_ptr<Base>`) which automatically execute virtual destructors correctly.
This study reference for Virtual Destructors in C++: Safe Cleanup Through Base-Class Pointers is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: