Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) dynamic_cast

 

dynamic_cast is a keyword to cast data types in the same inheritance hierarchy, for example an Animal to a Monkey.

 

 

There are two types of dynamic_cast:

  1. From a derived class to a base class (for example, from a Monkey to an Animal): this is called an upcast and will always succeed (as every Monkey is an Animal)
  2. From a base class to a derived class (for example, from an Animal to a Monkey): this is called a downcast and will not always succeed (as not every Animal is a Monkey). If a downcast cannot succeed, dynamic_cast returns an empty pointer

 

 

It is not possible to use dynamic_cast on smart pointers, use boost::dynamic_pointer_cast instead.

 

 

 

 

 

Example

 

 

 

 

 

 

Advice

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 22.7. Advice. page 663: '[2] Use dynamic_cast where class hierarchy navigation is unavoidable'
  2. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 22.7. Advice. page 663: '[3] Use dynamic_cast for type-safe explicit navigation of a class hierarchy'
  3. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 22.7. Advice. page 663: '[4] Use dynamic_cast to a reference type when failure to find the required class is considered a failure'
  4. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 22.7. Advice. page 663: '[5] Use dynamic_cast to a reference type when failure to find the required class is considered a valid alternative'
  5. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 22.7. Advice. page 663: '[10] Prefer virtual functions to repeated switch-statements based on typeid or dynamic_cast'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml