Dynamic-cast TypecastDynamic casts are only available in C++ and only make sense when applied to members of a class hierarchy ("polymorphic types"). Dynamic casts can be used to safely cast a superclass pointer (or reference) into a pointer (or reference) to a subclass in a class hierarchy. If the cast is invalid because the the real type of the object pointed to is not the type of the desired subclass, the dynamic will fail gracefully.
Pointer dynamic castWhen casting a pointer, if the cast fails, the cast returns NULL. This provides a quick method of determining if a given object of a particular dynamic type.
The syntax for a pointer dynamic cast is
<type> *p_subclass = dynamic_cast<<type> *>( p_obj );
Reference dynamic castWhen casting a reference, it is not possible to return a NULL pointer to indicate failure; a dynamic cast of a reference variable will throw the exception std::bad_cast (from the <typeinfo> header).
<type> subclass = dynamic_cast<<type> &>( ref_obj );To be safe, all calls to dynamic_cast must either be unfailable or wrapped in a try/catch block.