Casting from a virtual base to a derived class, using any means other than dynamic_cast
has undefined behavior. The behavior for
dynamic_cast
is defined.
Note: As of C++17, the program is considered 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 behavior
D *pD2 = static_cast<D*>(pB); // Noncompliant - undefined behavior
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