Consider a pointer to a Circle inheriting Shape, which is deleted via the base pointer:
class Shape {
public:
~Shape() { std::cout#include <iostream> << "~Shape\n"; }
};
class Circle : public Shape {
public:
~Circle() { std::cout#include <iostream> << "~Circle\n"; }
};
Shape* s = new Circle();
delete s; // Undefined behaviour.The above program has undefined behaviour, but usually outputs:
~Shape
~Circle() never runs, so anything Circle owns, such as memory from new, is never freed.
Declaring the base class destructor virtual makes delete call the destructor of the object's actual type. The derived destructor runs first, then the base destructor:
class Shape {
public:
virtual ~Shape() { std::cout#include <iostream> << "~Shape\n"; }
};
class Circle : public Shape {
public:
~Circle() { std::cout#include <iostream> << "~Circle\n"; }
};
Shape* s = new Circle();
delete s;~Circle
~Shape
Once the base class destructor is virtual, every derived class destructor is virtual too (without needing the virtual keyword).
Note
If a class has any virtual functions, give it a virtual destructor too.
Dan