C++ › Casting & Conversions

What is dynamic_cast and when do you use it?

Intermediate

Answer

dynamic_cast safely converts pointers/references within a polymorphic class hierarchy (the base must have a virtual function), checking at run time using RTTI. On a pointer, it returns nullptr if the cast is invalid; on a reference, it throws std::bad_cast. Use it for safe downcasting when you must determine an object's dynamic type.
Base* b = getShape();
if (auto* c = dynamic_cast<Circle*>(b)) c->radius();
Real-world example A rendering loop dynamic_casts base pointers to handle specific shape subtypes safely.

Common follow-ups: What does it return on failure for a pointer? | Why must the base be polymorphic?