MISRAC++2023-15.1.1_a
In this section:
Synopsis
(Required) An object's dynamic type shall not be used from within its constructor or destructor
Enabled by default
Yes
Severity/Certainty
Medium/High

Full description
A virtual member function is called in a class constructor. This check is identical to CPU-ctor-call-virt, MISRAC++2008-12-1-1_a.
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.
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;
}