Sobes.tech
Junior — Middle

What is the purpose of the dynamic_cast operator in C++?

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 (classes with virtual functions). It allows checking at runtime whether a pointer or reference to a base class can be safely cast to a pointer or reference to a derived class.

If the cast is possible, dynamic_cast returns a valid pointer or reference; if not, it returns nullptr (for pointers) or throws a std::bad_cast exception (for references).

Example:

class Base {
public:
    virtual ~Base() {}
};
class Derived : public Base {};

Base* b = new Derived();
Derived* d = dynamic_cast<Derived*>(b); // successful cast

Base* b2 = new Base();
Derived* d2 = dynamic_cast<Derived*>(b2); // nullptr, because b2 does not point to a Derived

Thus, dynamic_cast helps safely work with polymorphic objects and avoid undefined behavior when casting types incorrectly.