What does RTTI provide through typeid and dynamic_cast, when is polymorphism required, and when is virtual dispatch better?
Show answer and explanation
typeid reports static type for most expressions, but for a glvalue naming a polymorphic object it reports the dynamic type; applying it through a null polymorphic pointer expression can throw bad_typeid. dynamic_cast performs checked downcasts or cross-casts through a polymorphic hierarchy, returning null for failed pointer casts and throwing bad_cast for failed reference casts. RTTI is useful when type discovery is truly part of the operation, such as tooling or heterogeneous boundaries. If behavior belongs to the base contract, a virtual function or another explicit dispatch design usually avoids growing type tests and preserves substitutability.
typeid reports static type for most expressions, but for a glvalue naming a polymorphic object it reports the dynamic type; applying it through a null polymorphic pointer expression can throw bad_typeid. dynamic_cast performs checked downcasts or cross-casts through a polymorphic hierarchy, returning null for failed pointer casts and throwing bad_cast for failed reference casts. RTTI is useful when type discovery is truly part of the operation, such as tooling or heterogeneous boundaries. If behavior belongs to the base contract, a virtual function or another explicit dispatch design usually avoids growing type tests and preserves substitutability.
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.