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>
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.