When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used, and what risks does each carry?
Show answer and explanation
static_cast expresses supported compile-time conversions but an unchecked base-to-derived downcast is unsafe when the dynamic object has the wrong type. dynamic_cast performs checked casts in a polymorphic hierarchy, returning null for a failed pointer cast or throwing std::bad_cast for a failed reference cast. const_cast changes cv-qualification, yet modifying an object that was originally const is undefined behavior; reinterpret_cast performs low-level representation-oriented conversions but does not create an object, fix alignment, or permit forbidden aliasing. Named casts expose intent and should remain as narrow and local as possible.
static_cast expresses supported compile-time conversions but an unchecked base-to-derived downcast is unsafe when the dynamic object has the wrong type. dynamic_cast performs checked casts in a polymorphic hierarchy, returning null for a failed pointer cast or throwing std::bad_cast for a failed reference cast. const_cast changes cv-qualification, yet modifying an object that was originally const is undefined behavior; reinterpret_cast performs low-level representation-oriented conversions but does not create an object, fix alignment, or permit forbidden aliasing. Named casts expose intent and should remain as narrow and local as possible.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.