![]() |
VOOZH | about |
dynamic_cast is a runtime type conversion operator used in polymorphic inheritance hierarchies. It performs runtime type checking to ensure that a conversion is valid before it is applied.
Dynamic Cast Successful
Explanation: dynamic_cast safely converts a base class pointer to a derived class pointer at runtime. If the conversion is valid, it returns the converted pointer; otherwise, it returns nullptr
dynamic_cast<new_type>(expression)
Parameters
Return Value
Note: dynamic_cast relies on Run-Time Type Information (RTTI), which introduces some runtime overhead. If a conversion is guaranteed to be valid, static_cast is generally more efficient.
dynamic_cast is commonly used to safely convert a base class pointer to a derived class pointer.
Casting Successful
Explanation:
For downcasting to work, the base class must be polymorphic. A class becomes polymorphic when it contains at least one virtual function.
Example: Non-Polymorphic Base Class
Output
main.cpp: In function ‘int main()’:
main.cpp:24:21: error: cannot ‘dynamic_cast’ ‘bp’ (of type ‘class Base*’) to type ‘class Derived1*’ (source type is not polymorphic)
24 | Derived1* dp2 = dynamic_cast<Derived1*>(bp);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
Explanation
A cast fails when the actual object type does not match the target type.
Casting Failed
Explanation
When casting references, a failed conversion results in an exception instead of returning nullptr.
Output
main.cpp:31:15: warning: unused variable ‘dp2’ [-Wunused-variable]
31 | Derived1* dp2 = dynamic_cast<Derived1*>(bp);
| ^~~
std::bad_cast
Explanation