### 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:

- the name of a class
- an expression that evaluates to an object

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

The typeid operator returns a reference to a std::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 { /* . . . */ };

using namespace std;

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 std::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