[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]


Using the typeid Operator

The typeid operator lets you determine the type of an object. Like the sizeof operator, it takes two kinds of arguments:


NOTE

Whenever you use typeid operator, you must #include the typeinfo header file.

The typeid operator returns a reference to a type_info object that you can compare with the == and != operators. For example, if you have these classes and objects:


class Person { /* . . . */ };
class Athlete : public Person { /* . . . */ };

Person *lois = new Person;
Athlete *arnold = new Athlete;
Athlete *louganis = new Athlete;

All these expressions are true:


#include <typeinfo>
// . . .
if (typeid(Athlete) == typeid(*arnold))
   // arnold is an Athlete, result is true
if (typeid(*arnold) == typeid(*louganis))
   // arnold and louganis are both Athletes, result is true
if (typeid(*lois) == typeid(*arnold)) // ...
   // lois and arnold are not the same type, result is false

You can access the name of a type with the name() member function in the type_info class. For example, these statements:


#include <typeinfo>
// . . .
cout << "Lois is a(n) " 
     << typeid(*lois).name() << endl;
cout << "Arnold is a(n) " 
     << typeid(*arnold).name() << endl;

Print this:


Lois is a(n) Person
Arnold is a(n) Athlete


[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]

Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.

Last updated: August 17, 2000