Base classes need a virtual destructor in C++ because deleting a derived object through a base pointer is undefined behaviour without one. The same family of problems produces object slicing, where assigning a derived object to a base object silently throws away the derived part. Both bugs are invisible in the small programs and catastrophic in the large ones, and both are prevented by two small changes to how you write the base class and how you store the objects.
The previous lesson in this module covered "What Are Abstract Classes and Pure Virtual Functions?", and the next lesson in this module is about "How Does Polymorphism Shape Real Class Designs?".
The rule for polymorphic deletion
If you intend to delete an object through a pointer to a base class, then that base class must have a virtual destructor.
#include <iostream>
#include <string>
class Shape {
public:
explicit Shape(const std::string& name) : name_(name) {
std::cout << "creating " << name_ << '\n';
}
~Shape() {
std::cout << "destroying " << name_ << '\n';
}
const std::string& name() const { return name_; }
private:
std::string name_;
};
class Square : public Shape {
public:
explicit Square(double side) : Shape("square"), side_(side) {
std::cout << " side is " << side_ << '\n';
}
~Square() {
std::cout << " square specific cleanup\n";
}
private:
double side_;
};
int main() {
Shape* shape = new Square(3.0);
delete shape;
return 0;
}The output shows the problem. The derived destructor never ran.
creating square
side is 3
destroying squareThe Square destructor should have printed "square specific cleanup". It did not, because the delete through a Shape pointer called the Shape destructor and nothing more. Any resource that the derived class owned, such as a file handle, a buffer or a lock, would have leaked.
Adding virtual fixes it
#include <iostream>
#include <string>
class Shape {
public:
explicit Shape(const std::string& name) : name_(name) {
std::cout << "creating " << name_ << '\n';
}
virtual ~Shape() {
std::cout << "destroying " << name_ << '\n';
}
const std::string& name() const { return name_; }
private:
std::string name_;
};
class Square : public Shape {
public:
explicit Square(double side) : Shape("square"), side_(side) {
std::cout << " side is " << side_ << '\n';
}
~Square() override {
std::cout << " square specific cleanup\n";
}
private:
double side_;
};
int main() {
Shape* shape = new Square(3.0);
delete shape;
return 0;
}Now both of the destructors run, in the right order.
creating square
side is 3
square specific cleanup
destroying squareAnd the rule has a useful exception. If a base class is never used polymorphically, which means that it has no derived classes, no base pointers and no virtual functions, then a virtual destructor is unnecessary. But adding one costs nothing beyond a vtable pointer, so the pragmatic advice is to add it to every base class that has derived classes.
Object slicing
Slicing happens when a derived object is copied into a base object by value. The derived part is silently discarded.
#include <iostream>
#include <string>
class Shape {
public:
explicit Shape(const std::string& name) : name_(name) {}
virtual ~Shape() = default;
virtual const char* kind() const { return "shape"; }
private:
std::string name_;
};
class Square : public Shape {
public:
explicit Square(double side) : Shape("square"), side_(side) {}
const char* kind() const override { return "square"; }
private:
double side_;
};
int main() {
Square square(3.0);
Shape sliced = square; // the Square part is thrown away
std::cout << "sliced kind: " << sliced.kind() << '\n';
Shape* pointer = □ // no slicing: the object is unchanged
std::cout << "pointer kind: " << pointer->kind() << '\n';
return 0;
}The output shows the slice falling back to the base behaviour.
sliced kind: shape
pointer kind: squareAnd slicing is a compile-time-success and run-time-wrong bug. Nothing warns you about it, which is why the rule that you never store derived objects by value in a base container matters.
How to store a collection of shapes
There are three safe options.
The first one is to store base pointers. That is simple, but the ownership is manual and it is easy to leak.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual const char* kind() const = 0;
};
class Square : public Shape {
public:
explicit Square(double side) : side_(side) {}
double area() const override { return side_ * side_; }
const char* kind() const override { return "square"; }
private:
double side_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Square>(3.0));
for (const auto& shape : shapes) {
std::cout << shape->kind() << ": " << shape->area() << '\n';
}
return 0;
}The second one is to store smart pointers, and that is the usual choice. The std::unique_ptr knows the real type of the object and it deletes it correctly.
The third one is to use a container of derived objects. A std::vector can hold derived objects directly as long as you never mix the types, in which case there is no slicing.
The complete safe pattern
Combining everything, a base class designed for polymorphic use looks like this.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Shape {
public:
Shape() = default;
Shape(const Shape&) = default;
Shape& operator=(const Shape&) = default;
Shape(Shape&&) noexcept = default;
Shape& operator=(Shape&&) noexcept = default;
virtual ~Shape() = default;
virtual double area() const = 0;
virtual const char* kind() const = 0;
void report() const {
std::cout << kind() << " has area " << area() << '\n';
}
};
class Square : public Shape {
public:
explicit Square(double side) : side_(side) {}
double area() const override { return side_ * side_; }
const char* kind() const override { return "square"; }
private:
double side_;
};
class Circle : public Shape {
public:
explicit Circle(double radius) : radius_(radius) {}
double area() const override { return 3.14159 * radius_ * radius_; }
const char* kind() const override { return "circle"; }
private:
double radius_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Square>(3.0));
shapes.push_back(std::make_unique<Circle>(2.0));
for (const auto& shape : shapes) {
shape->report();
}
return 0;
}The output shows the safe pattern working.
square has area 9
circle has area 12.5664And nothing is leaked, nothing is sliced, and the destructor of the vector releases every shape through the virtual destructor.
Quick reference
- Deleting a derived object through a base pointer requires a virtual destructor in the base. Without one the derived destructor never runs and its resources leak.
- Object slicing silently discards the derived part when you copy by value into a base.
- Store the derived objects as pointers or smart pointers when the type varies.
- A base class with virtual functions should also declare the copy and the move operations as defaulted.
- A virtual destructor is only strictly needed when the base is used polymorphically.
Try it yourself: write a base class with a derived class that owns a resource in its destructor, delete it through a base pointer, and watch the derived destructor fail to run. Add the virtual keyword and confirm that it now runs. Next, assign a derived object to a base object by value and print what you get, and then use a reference instead and compare.