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.1
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 that are not invoked using a member of the class.
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 R2013b1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.