If T is “pointer to cv1B” and v has
type “pointer to cv2D” such that B is a base
class of D, the result is a pointer to the unique B
subobject of the D object pointed to by v, or
a null pointer value if v is a null pointer value.
Similarly, if
T is “reference to cv1B” and v has
type cv2D such that B is a base class of
D, the result is the unique B subobject of the D
object referred to by v.51
In both the pointer and
reference cases, the program is ill-formed if B is an inaccessible or
ambiguous base class of D.
[Example 1: struct B {};
struct D : B {};
void foo(D* dp){
B* bp =dynamic_cast<B*>(dp); // equivalent to B* bp = dp;} — end example]
If v has type “pointer to cvU” and
v does not point to an object
whose type is similar ([conv.qual]) to U and
that is
within its lifetime or
within its period of construction or destruction ([class.cdtor]),
the behavior is undefined.
If v is a glvalue of type U and
v does not refer to an object
whose type is similar to U and
that is
within its lifetime or
within its period of construction or destruction,
the behavior is undefined.
If, in the most derived object pointed (referred) to by v,
v points (refers) to a public base class subobject of a
C object, and if only one object of type C is derived
from the subobject pointed (referred) to by v,
the result points (refers) to that C object.
Otherwise, if v points (refers) to a public base
class subobject of the most derived object, and the type of the most
derived object has a base class, of type C, that is unambiguous
and public, the result points (refers) to the
C subobject of the most derived object.
[Example 2: class A {virtualvoid f(); };
class B {virtualvoid g(); };
class D :publicvirtual A, private B {};
void g(){
D d;
B* bp =(B*)&d; // cast needed to break protection
A* ap =&d; // public derivation, no cast needed
D& dr =dynamic_cast<D&>(*bp); // fails
ap =dynamic_cast<A*>(bp); // fails
bp =dynamic_cast<B*>(ap); // fails
ap =dynamic_cast<A*>(&d); // succeeds
bp =dynamic_cast<B*>(&d); // ill-formed (not a runtime check)}class E :public D, public B {};
class F :public E, public D {};
void h(){
F f;
A* ap =&f; // succeeds: finds unique A
D* dp =dynamic_cast<D*>(ap); // fails: yields null; f has two D subobjects
E* ep =(E*)ap; // error: cast from virtual base
E* ep1 =dynamic_cast<E*>(ap); // succeeds} — end example]