next up previous index
Next: RTTI Operation: Pointer Up: The Type_info Class Previous: RTTI Operation: Type

RTTI Operation: Typeid Comparison and Casting

As previously described, typeids can be compared for equality by their operator==() or for inheritance relationship by the can_cast() method.

The comparison operator for typeids will compare their Type_info pointers. If the comparison fails, it will compare 'deeper', i.e. the textual type names stored in the typeids. One could wonder why should a deep compare be necessary if there is exactly one Type_info instance per C++ class and the names of the C++ classes are unique in a program. The answer is that there is an additional case when Type_infos are created (see Section 4.4 and therefore there may be cases when there are several Type_info objects with the same name.

The can_cast() method basically finds out if a given Type_info t1 represents a base class of another given Type_info t2 . In order to implement this, Type_infos have to store ancestor relationships. Similarly to C++ class inheritance where a class declares its direct bases, a Type_info will store pointers to the Type_infos representing the direct base types of its type. This information is passed to Type_info at construction time. The Type_info objects will therefore create a graph isomorphic to the inheritance graph created by their C++ classes (Figure 4). Having this data, can_cast() simply reduces to a recursive search for t1 in the Type_info graph rooted at t2.

  
Figure 4: Implementation of type comparison and casting in the Type_info class.



Alexandru Telea