What is dynamic casting in C++?
A cast is an operator that forces one data type to be converted into another data type. In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference). It can also be used for upcasting; i.e., casting a derived class pointer (or reference) to a base class pointer (or reference).
Dynamic casting checks consistency at runtime; hence, it is slower than static cast.
Take a look at the function signature of the dynamic cast below:
To use
dynamic_cast<new_type>(ptr)the base class should contain at least one virtual function.
Code
In the example below, Shape is the parent class, and it has two derived classes: Square and Rectangle. The method dynamic_cast<Square*>(quad) successfully casts the base class pointer to the derived class pointer. However, since casting a derived class pointer to a base class pointer, and then casting this base class pointer into some other derived class pointer is invalid, dynamic_cast<Square*>(quad1) returns a NULL pointer.
Free Resources