When a class with no virtual
destructor is used as a base class, surprises can occur if pointers to instances of this class are used. Specifically, if an instance of a derived class is delete
d through a pointer to the base type, the behavior is undefined and can lead to resource leaks, crashes or corrupted memory.
If it is not expected for base class pointers to be deleted, then the destructor should be made protected
to avoid such a misuse.
Noncompliant Code Example
class Base { // Noncompliant: no destructor is supplied, and the default version is not virtual
public:
Base() {}
virtual void doSomething() {}
};
class Derived : public Base {
}
void f() {
Base *p = new Derived();
delete p; // Undefined behavior
}
Compliant Solution
class Base {
public:
Base() {}
virtual ~Base() = default;
virtual void doSomething() {}
};
See
- CERT, OOP52-CPP. - Do not delete a polymorphic object without a virtual destructor
- Virtuality article
- C++ Core Guidelines C.35 - A base class destructor should be either public and virtual, or protected and nonvirtual
- C++ Core Guidelines C.127 - A class with a virtual function should have a virtual or protected destructor