This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 8.2.1
Category: Required
Analysis Type: Decidable,Single Translation Unit
Amplification
This rule applies to both pointer and reference casts.
Rationale
The behaviour when casting from a virtual base class to a derived class is only well defined when dynamic_cast
is used, whilst the use
of the other casts can result in undefined behaviour. Since C++17, a static_cast
from a virtual base class is now
ill-formed, but some compilers may not yet issue a diagnostic. This rule ensures that all cases are detected.
Example
class B { };
class D: public virtual B { };
D d;
B * pB = &d;
D * pD1 = reinterpret_cast< D * >( pB ); // Non-compliant
D * pD2 = dynamic_cast< D * >( pB ); // Compliant - pD2 may be null
D & D3 = dynamic_cast< D & >( *pB ); // Compliant - may throw an exception
Copyright The MISRA Consortium Limited © 2023