MISRA C++:2008 Rule 12-1-1
An object's dynamic type shall not be used from the body of its constructor or destructor
Description
Rule Definition
An object's dynamic type shall not be used from the body of its constructor or destructor.
Rationale
The dynamic type of an object is the type of its most derived class. For instance:
struct B { virtual ~B() {} }; struct D: B {}; D d; B* ptr = &d;
*ptr
is
D
because that is the most derived class in the polymorphic
hierarchy.When you invoke the dynamic type of a polymorphic object in its constructor or destructor, you might get the type of the constructed or destroyed object instead of the type of the most derived object. This is because when you invoke the dynamic type during construction or destructor, the derived classes might not be constructed yet. Using dynamic types in constructors and destructors might result in unexpected behavior. Calling pure virtual functions from constructors and destructors results in undefined behavior. Avoid using the dynamic type of an object in its constructors or destructors.
Polyspace Implementation
Polyspace® flags these items when they are used in a constructor or a destructor of a polymorphic class:
The operator
typeid
Virtual or pure virtual functions
The function
dynamic_cast
or implicit C-style casts
Polyspace assumes that a class is polymorphic if it has any virtual member.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Special Member Functions |
Category: Required |
Version History
Introduced in R2013b