In C++, declaring a virtual destructor is useful when you have a polymorphic base class (a class with at least one virtual function) and you intend to derive from it. The destructor should be virtual to ensure that the correct destructor is called when deleting an object through a pointer to the base class.
Should the Virtual Destructor Be Empty?
Yes, a virtual destructor can (and often should) be empty if the base class has no resources to clean up. The key point is that it must be virtual to enable proper polymorphic destruction.
Why is a Virtual Destructor Needed?
If a base class does not have a virtual destructor, deleting a derived object through a base pointer leads to undefined behavior (typically, only the base destructor runs, causing memory leaks or corruption).
Example Without a Virtual Destructor (Problematic)
class Base {
public:
// Non-virtual destructor (BAD if derived classes exist)
~Base() { std::cout << "Base destructor\n"; }
};
class Derived : public Base {
public:
~Derived() { std::cout << "Derived destructor\n"; }
};
int main() {
Base* obj = new Derived();
delete obj; // Only ~Base() is called, ~Derived() is skipped!
return 0;
}
Output:
Base destructor
(Memory leak or corruption if Derived had resources!)
Example With a Virtual Destructor (Correct)
class Base {
public:
// Virtual destructor (GOOD for polymorphism)
virtual ~Base() { std::cout << "Base destructor\n"; }
};
class Derived : public Base {
public:
~Derived() override { std::cout << "Derived destructor\n"; }
};
int main() {
Base* obj = new Derived();
delete obj; // Correctly calls ~Derived() first, then ~Base()
return 0;
}
Output:
Derived destructor
Base destructor
(Proper cleanup!)
When Should the Virtual Destructor Be Empty?
- If the base class has no resources to clean up (e.g., no dynamic memory, file handles, etc.), the destructor can be empty.
- The important part is that it is
virtual, not whether it has logic inside.
Best Practices
- Always declare a virtual destructor in polymorphic base classes (even if empty).
- Avoid making destructors
virtual unnecessarily (if the class is not meant to be inherited from).
- If the base class has no virtual functions but is still meant to be inherited from, consider making the destructor
virtual (or at least document the requirement for derived classes to handle destruction properly).
Conclusion
An empty virtual destructor is perfectly fine and often necessary in C++ when dealing with polymorphism. The key is ensuring proper destruction behavior, not whether the destructor contains cleanup logic.