C++ · Intermediate level

Intermediate level · Module 2: Inheritance and Virtual Functions · Lesson 3 of 3

Virtual Destructors and Object Slicing

Avoid two classic polymorphism bugs: deleting through a base pointer without a virtual destructor, and slicing derived objects.

In this lesson you will

  • Give polymorphic base classes virtual destructors
  • Recognise and prevent object slicing

Key concepts

virtual destructorobject slicingpass by referencestd::unique_ptr<Base>

The lesson

If a derived object is deleted through a base pointer and the base destructor is not virtual, the behaviour is undefined — typically the derived part is never cleaned up. Every class meant to be used polymorphically needs virtual ~Base() = default;.

Slicing happens when a derived object is copied into a base object, for example by passing it by value to a function taking Staff. Only the base part is copied, and virtual calls use the base version. Pass polymorphic objects by reference or pointer.

Store polymorphic objects in containers as std::unique_ptr<Base>, never as Base values; std::vector<Staff> would slice every derived object added to it.

Step by step

  1. Remove the virtual destructor and observe the derived destructor not running.
  2. Restore it and observe correct cleanup.
  3. Pass a Doctor by value to a function taking Staff and observe the wrong pay.
  4. Change the parameter to const Staff& and confirm the fix.

Practice activity

Find and fix the slicing and destructor bugs in a provided staff program.

Expected result: All derived destructors run and every function uses the correct derived behaviour.

Check your understanding

  1. Why does a polymorphic base class need a virtual destructor?

    Show answer

    So deleting a derived object through a base pointer runs the derived destructor.

  2. What is object slicing?

    Show answer

    Copying a derived object into a base object, losing the derived part.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.