Avoid Classes with at least one virtual Function and without a virtual Destructor | CAST Appmarq

Avoid Classes with at least one virtual Function and without a virtual Destructor


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++

Health Factor

  Total Quality Index


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.

Benchmark Statistics

Global Compliance

96.97%

Total Violations
11,957
Total Opportunities
394,601
Average Violations / App.
72.47
The compliance score represents 1 minus the ratio between the number of times a rule has been violated compared to the number of opportunities in a set of applications that the rule could have been violated.

Industry Insights

Software ISV

96.84%

Select from drop-down

91.64%

Financial Services

97.31%