C++ › Casting & Conversions
What is the difference between static_cast and dynamic_cast for downcasting?
AdvancedAnswer
static_cast downcasts without any runtime check—fast, but undefined behavior if the object isn't actually of the target type. dynamic_cast checks the actual dynamic type at runtime (using RTTI) and returns nullptr (pointers) or throws (references) if the cast is invalid, making it safe but slower and requiring a polymorphic base. Use dynamic_cast when correctness of the type isn't guaranteed.
Derived* d1 = static_cast<Derived*>(base); // unchecked
Derived* d2 = dynamic_cast<Derived*>(base); // nullptr if wrongReal-world example static_cast is used when the type is known; dynamic_cast when handling heterogeneous base pointers safely.