First, CBase
must be polymorphic in order for you to use dynamic_cast
here (that is, it must have at least one virtual
member function). Otherwise, you can't use dynamic_cast
.
That said, the cast of &b
to CDerived*
is not wrong: pd
will be a null pointer.
dynamic_cast
has the useful property that when the cast fails (that is, if the object pointed to by the pointer isn't of the target type), it yields a null pointer. This allows you to test the actual type of an object. For example:
CBase b;
CDerived d;
CBase* pb = &b;
CBase* pd = &d;
CDerived* xb = dynamic_cast<CDerived*>(pb); // xb is null!
CDerived* xd = dynamic_cast<CDerived*>(pd); // xd points to d!
Your code would have been incorrect if you had used static_cast
, since it casts without performing any runtime type check, which means there is no way to test whether the cast succeeded. If you ever need to cast down a class hierarchy and you don't know for certain whether the object is of the derived type to which you are trying to cast, you must use dynamic_cast
.