Declare virtual destructor for polymorphic base class

Photo by Billy Huynh on Unsplash

Declare virtual destructor for polymorphic base class

·

1 min read

Table of contents

There are lots of ways to keep track of time, so it would be reasonable to create a TimeKeeper base class along with derived classes for different approaches to timekeeping

class TimeKeeper {
public:
    TimeKeeper();
    ~TimeKeeper();
    ...
};

class AtomicClock : public TimeKeeper {...};    
class WaterClock : public TimeKeeper {...};
class WristWatch : public TimeKeeper {...};

To achieve polymorphism, our code is just like that

TimeKeeper *pTimeKeeper = new AtomicClock;
...
delete pTimeKeeper;    // Is it true that we release all resources?

This is a recipe for disaster because C++ specifies that when a derived class object is deleted through a pointer to a base class with a non-virtual destructor, results are undefined. What typically happens at runtime is that the derived part of the object is never destroyed. This is an excellent way to leak resources, corrupt data structures, and spend a lot of time with a debugger.

A correct solution

class TimeKeeper {
public:
    TimeKeeper();
    virtual ~TimeKeeper(); // add virtual to the destructor 
    ...
};


TimeKeeper *pTimeKeeper = new AtomicClock;
...
delete pTimeKeeper;    // The behavior is correct now