Dynamic Cast
Explore the use of dynamic_cast in C++ to convert pointers or references within an inheritance hierarchy. Understand how it enables up, down, and cross casting for polymorphic classes while ensuring safe runtime type validation and handling casting failures.
Features
-
dynamic_castconverts a pointer or reference of a class to a pointer or reference in the same inheritance hierarchy. -
It can only be used with polymorphic classes. With
dynamic_cast, we cast up, down, and across the inheritance hierarchy. -
Type information at run time is used to determine if the cast is valid.
-
If the cast is not possible, we will get a
nullptrin case of a pointer, and anstd::bad_cast-exceptionin case of a reference. -
dynamic_castis mostly used when converting from a derived class to a base class, but can also work the opposite operation.
Example
The classes in the code above form the following hierarchy:
From line 23 onwards, we can see how up, down, and cross casting is possible with dynamic_cast.
Do keep in mind that
dynamic_castonly deals with pointers and references.