19.10.1.  typeid operator

[ fromfile: rtti.xml id: typeid ]

Another operator that is part of RTTI is typeid(),which returns type information about its argument. For example:

    void f(Person& pRef) {
       if(typeid(pRef) == typeid(Student) {
         // pRef is actually a reference to a Student object.
         // Proceed with Student specific processing.
       }
       else {
         // Nope! the object referred to by pRef is not a Student.
         // Proceed to do whatever alternative stuff is required.
       }
    }

typeid() returns a type_info object that corresponds to the argument's type.

If two objects are the same type, their type_info objects should be equal. The typeid() operator can be used for polymorphic types or nonpolymorphic types. It can also be used on basic types and custom classes. Furthermore, the arguments to typeid() can be type names or object names.

Following is one possible implementation of the type_info class, based on g++ 4.4:

class type_info {
 private:
    type_info(const type_info& );
    // cannot be copied by users
    type_info& operator=(const type_info&);
    // implementation dependent representation
 protected:
    explicit type_info(const char *name);
 public:
    virtual ~type_info();
    bool operator==(const type_info&) const;
    bool operator!=(const type_info&) const;
    bool before(const type_info& rhs) const;
    const char* name() const;
    // returns a pointer to the name of the type
    // [...]
}