Inheritance/Polymorphism  «Prev  Next»
Lesson 16 Runtime Type Identification
Objective The typeid operator and type_info class

C++ typeid Operator

Use the typeid operator instead of the virtual function

This page asks you to use the typeid operator instead of the virtual function you wrote to return the name of a shape as a char* value. The operator typeid() can be applied to a type name or to an expression to determine the exact type of the argument. The operator returns a reference to the class type_info, which is supplied by the system and is defined in the header file type_info.h.

Possible arguments of typeid()

Some possible arguments of typeid() are
  1. a reference to a class
  2. a pointer argument, dereferenced with *

Note: Borland C++ 4.0 uses typeinfo.h instead of type_info.h.
If you use MSVC, select the Run-Time Type Information (RTTI) option in order to enable the typeinfo.h utilities.
The class type_info provides a name() member function returning a string that is the type name. It also provides overloadedequality operators. Remember to check the local implementation for the complete interface of this class.

Base* bptr;
.....
//print the type name of what bptr currently points at
cout << typeid(bptr).name() << endl;
.....
if (typeid(bptr) == typeid(Derived)) {
//do something appropriate for Derived
.....
}

Typeid Operator - Exercise

Click the Exercise link below to use the typeid operator instead of the virtual function you wrote that returns the name of a shape as a char* value.
Typeid Operator - Exercise