Rule A12-4-1 (required, implementation, automated)
Destructor of a base class shall be public virtual, public override or protected non-virtual.
Rationale
If an object is supposed to be destroyed through a pointer or reference to its base class, the destructor in the base class needs to be virtual. Otherwise, destructors for derived types will not be invoked. Note that if it is prohibited to destroy an object through a pointer or reference to its base class, the destructor in the base class is supposed to be protected.
Example
// $Id: A12-4-1.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
class A
{
public:
~A() // Non-compliant
{
}
};
class B : public A
{
};
class C
{
public:
virtual ~C() // Compliant
{
}
};
class D : public C
{
};
class E
{
protected:
~E(); // Compliant
};
class F : public E
{
};
void F1(A* obj1, C* obj2)
{
// ...
delete obj1; // Only destructor of class A will be invoked
delete obj2; // Both destructors of D and C will be invoked
}
void F2()
{
A* a = new B;
C* c = new D;
F1(a, c);
}
See also
JSF December 2005 [8]: AV Rule 78 All base classes with a virtual function shall define a virtual destructor. HIC++ v4.0 [9]: 12.2.1 Declare virtual, private or protected the destructor of a type used as a base class. SEI CERT C++ Coding Standard [10]: OOP52-CPP: Do not delete a polymorphic object without a virtual destructor. C++ Core Guidelines [11]: C.35: A base class destructor should be either public and virtual, or protected and nonvirtual.
C++ Core Guidelines [11]: Discussion: Make base class destructors public and virtual, or protected and nonvirtual.