Skip to Main Content
C++ In a Nutshell
book

C++ In a Nutshell

by Ray Lischner
May 2003
Intermediate to advanced content levelIntermediate to advanced
808 pages
32h 24m
English
O'Reilly Media, Inc.
Content preview from C++ In a Nutshell

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.
Start your free trial

You might also like

C++ High Performance

C++ High Performance

Viktor Sehr, Björn Andrist
Optimized C++

Optimized C++

Kurt Guntheroth
Mastering C++ Programming

Mastering C++ Programming

Jeganathan Swaminathan

Publisher Resources

ISBN: 059600298XSupplemental ContentErrata Page