Junior — Middle
What is the difference between static_cast and dynamic_cast in C++, and when should they be used?
sobes.tech AI
Answer from AI
static_cast and dynamic_cast are type casting operators in C++, but they serve different purposes:
-
static_cast:
- Performs compile-time type conversion.
- Does not check the correctness of the cast at runtime.
- Used for conversions between compatible types, e.g., base to derived (without check), numeric types, pointers.
- Faster but unsafe when casting pointers in class hierarchies.
-
dynamic_cast:
- Performs runtime type checking (RTTI).
- Used for safe casting of pointers or references within inheritance hierarchies.
- Returns nullptr if the cast fails for pointers; throws std::bad_cast for references.
- Requires the base class to have at least one virtual function.
When to use:
- Use
static_castwhen you are sure about the types and want maximum performance. - Use
dynamic_castwhen you need to safely check the type at runtime, e.g., working with polymorphism and ambiguous hierarchies.
Example:
class Base { virtual void foo() {} };
class Derived : public Base {};
Base* b = new Derived();
// Safe cast with check
Derived* d1 = dynamic_cast<Derived*>(b); // nullptr if b is not Derived
// Unsafe cast without check
Derived* d2 = static_cast<Derived*>(b); // may lead to errors if b is not Derived