CPU-dtor-call-virt (C++ only)
Synopsis
A virtual member function is called in a class destructor.
Enabled by default
Yes
Severity/Certainty
Medium/High

Full description
When an instance is destroyed, the virtual member function of its base class is called, rather than the function of the actual class being destroyed. This might result in the incorrect function being called, and consequently dynamic memory might not be properly deallocated, or some other unwanted behavior might occur. This check is identical to MISRAC++2008-12-1-1_b, MISRAC++2023-15.1.1_b.
Coding standards
- CERT OOP30-CPP
Do not invoke virtual functions from constructors or destructors
- MISRA C++ 2008 12-1-1
(Required) An object's dynamic type shall not be used from the body of its constructor or destructor.
- MISRA C++ 2023 15.1.1
(Required) An object's dynamic type shall not be used from within its constructor or destructor
Code examples
The following code example fails the check and will give a warning:
#include <iostream>
class A {
public:
~A() { f(); } //virtual member function is called
virtual void f() const { std::cout << "A::f\n"; }
};
class B: public A {
public:
virtual void f() const { std::cout << "B::f\n"; }
};
int main(void) {
B *b = new B();
delete b;
return 0;
}
The following code example passes the check and will not give a warning about this issue:
#include <iostream>
class A {
public:
~A() { } //OK - contructor does not call any virtual
//member functions
virtual void f() const { std::cout << "A::f\n"; }
};
class B: public A {
public:
virtual void f() const { std::cout << "B::f\n"; }
};
int main(void) {
B *b = new B();
delete b;
return 0;
}