(C++) dynamic\_cast
February 24, 2017 · View on GitHub
(C++) 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:
- 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)
- 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
- Use dynamic_cast where class hierarchy navigation is unavoidable [1]
- Use dynamic_cast for type-safe explicit navigation of a class hierarchy [2]
- Use dynamic_cast to a reference type when failure to find the required class is considered a failure [3]
- Use dynamic_cast to a reference type when failure to find the required class is considered a valid alternative [4]
- Prefer virtual functions to repeated switch-statements based on typeid or dynamic_cast [5]
References
- 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'
- 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'
- 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'
- 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'
- 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'