RTTI
By using run-time types to identify--rtti, programs can use pointers or references to base classes to retrieve the actual derived class types of those pointers or references to the objects they refer to:
It is mainly implemented by two operators:
1.typeid--returns the actual type of the object that the pointer or reference refers to;
2.dynamic_cast--converts a pointer or reference of a base class type to a pointer or reference to a derived type safely;
dynamic_cast
You can use this operator instead of a virtual function when you cannot add a virtual function for a base class, and you use a pointer to a base class or a reference to a function that calls a derived class.
The pointer used with dynamic_cast must be valid-it must be 0 or point to an object.
Unlike other coercion type conversions, dynamic_cast involves run-time type checking, It performs two operations at a time: 1. It first verifies that the requested conversion is valid, that is, the object bound to the reference or pointer must be an object of the target type (or its derived object), if not, the binding fails, and if the binding fails, the result is 0 if the pointer type is converted, or if the reference type is converted to a bad An exception of type _cast. The exception is defined in the TypeInfo header file; 2. Conversion is actually performed only when the validation conversion is valid, and the conversion is run phase rather than compile phase;
typeID
The typeid operator can ask an expression to derive its type.
The expressions are as follows: typeID (e)
E can be still an expression or a type name, if it is a class type and the class contains one or more functions, the dynamic type of the expression may be different from its static type, the operator evaluates its type at run time, and if it is an expression (built-in type or constant), the operator will indicate the static type of E.
The result of the typeid operator is an object reference to the label library type named Type_info, which is contained in the header file TypeInfo.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + run-time type recognition--rtti