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
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?