Name
dynamic_cast operator — Polymorphic cast of class type objects
Synopsis
postfix-expr := dynamic_cast < type-id > ( expression )The dynamic_cast operator
performs a polymorphic cast on a pointer or reference to an object
of class type. If expression is a
pointer or reference to a base class, type-id can be a pointer or reference to a
derived class. If the dynamic type of the object is not that of
type-id or a class derived from
type-id, the cast fails. If
expression is a pointer, failure
returns a null pointer; if expression is a
reference, failure throws std::bad_cast. Casts from a derived to an
unambiguous, accessible base class always succeed.
If expression is a null
pointer, the result is a null pointer. If type-id is a pointer to void, the cast succeeds and returns a
pointer to the most-derived object that expression represents.
Example
struct base {};
struct derived : base {};
base* b = new derived;
derived* d =dynamic_cast<derived*>(b);See Also
const_cast, expression, reinterpret_cast, static_cast, type, Chapter
3, <typeinfo>
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access