Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

CWARN.DTOR.NONVIRT.NOTEMPTY

Inherited virtual functions in class but destructor is not virtual and not empty

The CWARN.DTOR.NONVIRT.NOTEMPTY checker flags classes in which the class declares virtual member functions inherited from its base class, but its destructor isn't virtual or empty.

Vulnerability and risk

When an object of a class derived from a base class is deleted through a pointer to the base class, the destructor of the derived class isn't executed, and members of the derived class aren't disposed of correctly. This situation can lead to leaked memory and unreleased resources.

Mitigation and prevention

It's important to provide a virtual destructor, even if it will be empty, in a class that contains a virtual method and some member data that must be properly disposed of, implicitly or explicitly. Derived classes will inherit from the base class, and if the base class destructor isn't defined as virtual, memory won't be deallocated properly. In a hierarchy of classes declaring or overriding virtual functions, the virtual destructor has to be defined only once, for the root class of the hierarchy.

Vulnerable code example

1   #include <iostream>
2   using namespace std; 
3    
4   class A
5   {
6   public:
7    
8       ~A() {std::cout << "I am A" << std::endl;}
9       virtual void f1();
10  };
11   
12  class B : public A
13  {
14  public:
15   
16      ~B() {cout << "I am B" << endl;} 
17      virtual void f1();
18  };

In this code example, the non-virtual destructor in class A means that Klocwork flags line 16.