MISRA C++:2023 Rule 8.2.1
A virtual base class shall only be cast to a derived class by means of
dynamic_cast
Since R2024b
Description
Rule Definition
A virtual base class shall only be cast to a derived class by means of
dynamic_cast. 1
Rationale
A virtual base implies that multiple classes might be derived from
it.
class Base{};
class childA: virtual public Base{};
class childB: virtual public Base{};
class childFinal: public childA, public childB{};;childA and childB share the same
instance of the class Base. The necessary pointer arithmetic is unknown
at compile time when you cast from Base* to childA* or
childB*. The offset of the child classes compared to
Base is known only at run time.Use dynamic_cast when downcasting a pointer to a virtual base class
into a pointer to a child class. Using any other casting operation for this purpose results
in an undefined behavior.
Polyspace Implementation
Polyspace® raises a violation if these conditions are met:
A virtual base class is downcast.
The casting operation is not done by using
dynamic_cast
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: Expressions |
| Category: Required |
Version History
Introduced in R2024b
1 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.