How do I use dynamic_cast safely?

The dynamic_cast operator in C++ is used for safe downcasting of polymorphic types. It ensures that the cast is valid at runtime by checking the actual object type before allowing the cast to proceed. If the cast is not valid, it returns nullptr for pointers or throws an exception for references. This makes it a safer option compared to traditional casts.

Using dynamic_cast Safely

To use dynamic_cast safely, you should always check the result of the cast operation. The following example demonstrates how to use dynamic_cast properly:

class Base { public: virtual ~Base() {} }; class Derived : public Base { public: void display() { std::cout << "Derived class" << std::endl; } }; void safeDynamicCast(Base* basePtr) { Derived* derivedPtr = dynamic_cast(basePtr); if (derivedPtr) { derivedPtr->display(); // Safe to use derivedPtr } else { std::cout << "Invalid cast" << std::endl; } }

dynamic_cast C++ type safety polymorphism runtime checking