Why do we need a virtual destructor in C++?
If you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs. This is undefined behavior, and the resources of the derived class leak.
#include <iostream>
#include <memory>
struct Base {
virtual ~Base() { std::cout << "~Base\n"; }
};
struct Derived : Base {
~Derived() override { std::cout << "~Derived\n"; }
};
int main() {
std::unique_ptr<Base> p = std::make_unique<Derived>();
} // both destructors run, because ~Base is virtual
Output
~Derived
~Base
Rule: a class which is used as a base class for polymorphism must have a virtual destructor (or a protected non virtual one). See Polymorphism.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |