Rule Definition
During construction and destruction of an object, its final type may be different from that of the completely constructed object. The result of using an object’s dynamic type in a constructor or destructor may not be consistent with developer expectations. The dynamic type of an object is used in the following construct:
- typeid on a class with a virtual function or a virtual function in a base class.
Remediation
Avoid using object's dynamic type in a constructor or a destructor
Violation Code Sample
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
typeid ( B2 ); // Non-compliant
}
};
Fixed Code Sample
class B1
{
public:
B1 ( )
{
typeid ( B1 ); // Compliant, B1 not polymorphic
}
};
Reference
MISRA C++ 2008, 12-1-1: An object’s dynamic type shall not be used from the body of its constructor or destructor.
AUTOSAR C++ 2014, M12-1-1: An object’s dynamic type shall not be used from the body of its constructor or destructor.
Related Technologies
Technical Criterion
Programming Practices - OO Inheritance and Polymorphism
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.