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() {}
};