Sobes.tech
Junior — Middle

Can you explain what the dynamic_cast operator in C++ means and what it is used for?

sobes.tech AI

Answer from AI

The dynamic_cast operator in C++ is used for safe casting of pointers or references within an inheritance hierarchy, especially when working with polymorphism.

It allows:

  • Converting a pointer or reference of a base class to a pointer or reference of a derived class.
  • Checking at runtime whether the object actually belongs to the target type.

If the conversion is not possible, dynamic_cast returns nullptr for pointers, and throws a std::bad_cast exception for references.

Example:

class Base { virtual void foo() {} };
class Derived : public Base {};

Base* b = new Derived();
Derived* d = dynamic_cast<Derived*>(b);
if (d) {
    // Conversion succeeded
} else {
    // Conversion failed
}