Back: The typename Keyword
Forward: Templates
 
FastBack: Compiler Quirks
Up: Changeable C++
FastForward: Compiler Quirks
Top: Autoconf, Automake, and Libtool
Contents: Table of Contents
Index: Index
About: About this document

16.2.9 Runtime Type Identification (RTTI)

Run-time Type Identification, or RTTI, is a mechanism for interrogating the type of an object at runtime. Such a mechanism is useful for avoiding the dreaded switch-on-type technique used before RTTI was incorporated into the language. Until recently, some C++ compilers did not support RTTI, so it is necessary to assume that it may not be widely available.

Switch-on-type involves giving all classes a method that returns a special type token that an object can use to discover its own type. For example:

 
        class Shape
        {
        public:
          enum types { TYPE_CIRCLE, TYPE_SQUARE };
          virtual enum types type () = 0;
        };

        class Circle: public Shape
        {
        public:
         enum types type () { return TYPE_CIRCLE; }
        };

        class Square: public Shape
        {
        public:
          enum types type () { return TYPE_SQUARE; }
        };

Although switch-on-type is not elegant, RTTI isn't particularly object-oriented either. Given the limited number of times you ought to be using RTTI, the switch-on-type technique may be reasonable.


This document was generated by Gary V. Vaughan on February, 8 2006 using texi2html