TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  OOP#013Checked automatically with code checker

Synopsis:A public base class must have either a public virtual destructor or a protected destructor
Language:C++
Severity Level:1
Category:Object Oriented Programming


Description:

The problem that is addressed in this rule is the following. Have a look at the following code that results in undefined behaviour:

class Base { // no virtual destructor ... }; class Derived : Base { ~Derived() { /* ... do some cleanup ... */ } ... }; ... Base* b = new Derived(); delete b; // undefined behavior!!!

The undefined behaviour occurs when one tries to delete an instance of a derived class through a pointer of the base class. This problem can be avoided in 2 ways: either specify a public virtual destructor or a protected destructor. The first case, declaring the Base destructor public and virtual is shown below:

class Base { public: virtual ~Base() { /* ... do some cleanup ... */ } ... }; class Derived : Base { ~Derived() { /* ... do some cleanup ... */ } ... }; ... Base* b = new Derived(); delete b; // works fine

This makes sure the Base destructor becomes accessible and is called automatically after the Derived constructor is called. The other solution is to make sure that this situation can never happen. This is done by declaring the Base destructor non-virtual and protected:

class Base { protected: ~Base() { /* ... do some cleanup ... */ } ... }; class Derived : Base { ~Derived() { /* ... do some cleanup ... */ } ... }; ... Base* b = new Derived(); delete b; // won't compile

In this case the Base destructor is not accessible from within the Derived class. It just won't compile.



Literature References:
C++ Core Guidelines Rule C.35