Next: RTTI
Support for Up: A
General-Purpose Run-Time Type Previous: The
Concept of
Uses of Run-Time Type Information
If we have a means to obtain a typeid from a pointer, reference or class,
we can provide a couple of useful operations on typeids:
- 1. Type names: Given a typeid, which is an abstract encoding
of a type, we would like to obtain a textual representation of it. For
example, for a C++ class A, we would like to obtain a character
string "A" from its typeid.
- 2. Typeid comparison: Given two typeids, we should be able to
determine if they represent the same type or if they represent types related
by inheritance or unrelated types.
- 3. Pointer and reference casting: Given a pointer and a typeid,
we can determine if the actual pointed object is of the type represented
by that typeid. Furthermore, we could cast a given pointer p to
a C++ type encoded by a given typeid t at runtime and, if the cast
succeeds, return a pointer p' of type t.
- 4. Run-time object creation: Given a typeid t, we would
like to create an object of type t and return it as a a pointer
of type t.
Operation 1 allows us to compare types at run-time and determine their
relationship (e.g. subclass to superclass). Operation 2 maps types to a
textual representation which can be necessary if the user desires to be
given type information in a readable way. Operation 3 gives the possibility
to cast pointers and references at run-time, which is mostly used in the
form of downcasts, i.e. casts from a base type to a derived type
and gives the possibility to interpret a pointer in a different way. Operation
4 allows a program to postpone the decision of creating new objects until
run-time and then create objects from run-time selected types.
Next: RTTI
Support for Up: A
General-Purpose Run-Time Type Previous: The
Concept of
Alexandru Telea