Why is this an issue?
Casting from a virtual base to a derived class, using any means other than dynamic_cast has undefined behaviour. The behaviour for dynamic_cast is
defined.
Note: As of C++17, the program is considered as ill-formed and an error is reported.
Most compilers emit an error for previous versions of C++ as well.
Noncompliant code example
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
D *pD1 = ( D * ) pB; // Noncompliant - undefined behaviour
D *pD2 = static_cast<D*>(pB); // Noncompliant - undefined behaviour
Compliant solution
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
D *pD1 = dynamic_cast<D*>(pB); // Compliant, but pD2 may be NULL
D & D2 = dynamic_cast<D&>(*pB); // Compliant, but may throw an exception
Resources
- MISRA C++:2008, 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.