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:

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

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.

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved