CPU-nonvirt-dtor (C++ only)
In this section:
Synopsis
A public non-virtual destructor is defined in a class with virtual methods.
Enabled by default
Yes
Severity/Certainty
Medium/High

Full description
A public non-virtual destructor is defined in a class with virtual methods. Calling delete on a pointer to any class derived from this one might call the wrong destructor. If any class might be a base class (by having virtual methods), then its destructor should be either be virtual or protected so that callers cannot destroy derived objects via pointers to the base.
Coding standards
- CERT OOP34-CPP
Ensure the proper destructor is called for polymorphic objects
Code examples
The following code example fails the check and will give a warning:
#include <iostream>
class Base
{
public:
Base() { std::cout<< "Constructor: Base" << std::endl;}
virtual void f(void) {}
//non-virtual destructor:
~Base() { std::cout<< "Destructor : Base" << std::endl;}
};
class Derived: public Base
{
public:
Derived() { std::cout << "Constructor: Derived" << std::endl;}
void f(void) { std::cout << "Calling f()" << std::endl; }
virtual ~Derived() { std::cout << "Destructor : Derived" << std::endl;}
};
int main(void)
{
Base *Var = new Derived();
delete Var;
return 0;
}
The following code example passes the check and will not give a warning about this issue:
#include <iostream>
class Base
{
public:
Base() { std::cout << "Constructor: Base" << std::endl;}
virtual void f(void) {}
virtual ~Base() { std::cout << "Destructor : Base" << std::endl;}
};
class Derived: public Base
{
public:
Derived() { std::cout << "Constructor: Derived" << std::endl;}
void f(void) { std::cout << "Calling f()" << std::endl; }
~Derived() { std::cout << "Destructor : Derived" << std::endl;}
};
int main(void)
{
Base *Var = new Derived();
delete Var;
return 0;
}