This paper presents such a system which implements type variables (typeids), generalized pointer casting and object construction from run-time supplied typeids. A simple method to add these facilities to any C++ class hierarchy is presented.
Introduction
Run-time type information (RTTI) can be seen as an extension to static (compile-time) type information. It offers to the user information about pointers and references which is similar to the type information a compilermaintains while compiling a C++ program.
Basically, RTTI comes in two flavours: getting type information from run-time elements like pointers and references and getting type information from 'static' elements like classes.
Since this information is to be passed to the user (who will manipulate it at runtime), we need a way to encode it in some run-time object. Such an object is called a typeid and keeps all information which characterizes a C++ type. In other words, for any C++ type there is a typeid object which encodes its type. In the rest of this paper we shall identify the C++ type concept with the C++ class concept, thus ignoring basic types like int, float, etc.
To precise notions, a typeid for a pointer or reference will represent the type of the actual object pointed by that pointer or referred to by that reference. The typeid for a class will obviously represent the type of that class.
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.
2 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 readableway. 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 ...