MISRA C++:2008 Rule 5-2-2
A pointer to a virtual base class shall only be cast to a pointer to a derived class
by means of dynamic_cast
Description
Rule Definition
A pointer to a virtual base class shall only be cast to a pointer to a derived
class by means of dynamic_cast
.
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 R2013b