Rule Definition
Whenever a virtual method is defined in a class, it means that the class is intended to be used in an inheritance hierarchy. In this context, a derived object will often be handled through a pointer to its base class, to achieve polymorphism. If a class has a non-virtual destructor, and an attempt is made to destroy an object of a derived type through a pointer to the base type, the behavior is undefined.
On some platforms, it may call the base-class version of the destructor instead of the derived-class version, provoking memory leaks, resource losses and stability issues. On others, it may simply crash.
Furthermore, once your class contains one virtual function, adding a virtual destructor does not add any additional per-object cost, so adding it is both free and safer.
Remediation
Add a virtual destructor to the class that has a virtual function.
Violation Code Sample
class CParent
{
~CParent();
virtual int foo();
};
Fixed Code Sample
class CParent
{
virtual ~CParent();
int virtual foo();
};
Reference
"C++ FAQ Lite [20.7] When should my destructor be virtual?":http://www.parashift.com/c++-faq-lite/virtual-functions.html##faq-20.7
Related Technologies
C++
Technical Criterion
CWE-1087 - Class with Virtual Method without a Virtual Destructor
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.