C++ Programming
- Syntax
typeid( object );
The typeid
operator is used to determine the class of an object at runtime. It returns a reference to a std::type_info
object, which exists until the end of the program, that describes the "object". If the "object" is a dereferenced null pointer, then the operation will throw a std::bad_typeid
exception.
Objects of class std::bad_typeid
are derived from std::exception
, and thrown by typeid
and others.
The use of typeid
is often preferred over dynamic_cast
<class_type>
in situations where just the class information is needed, because typeid
, applied on a type or non de-referenced value is a constant-time procedure, whereas dynamic_cast
must traverse the class derivation lattice of its argument at runtime. However, you should never rely on the exact content, like for example returned by std::type_info::name()
, as this is implementation specific with respect to the compile.
It is generally only useful to use typeid
on the dereference of a pointer or reference (i.e. typeid(*ptr)
or typeid(ref)
) to an object of polymorphic class type (a class with at least one virtual member function). This is because these are the only expressions that are associated with run-time type information. The type of any other expression is statically known at compile time.
- Example
#include <iostream>
#include <typeinfo> //for 'typeid' to work
class Person {
public:
// ... Person members ...
virtual ~Person() {}
};
class Employee : public Person {
// ... Employee members ...
};
int main () {
Person person;
Employee employee;
Person *ptr = &employee;
// The string returned by typeid::name is implementation-defined
std::cout << typeid(person).name() << std::endl; // Person (statically known at compile-time)
std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)
std::cout << typeid(ptr).name() << std::endl; // Person * (statically known at compile-time)
std::cout << typeid(*ptr).name() << std::endl; // Employee (looked up dynamically at run-time
// because it is the dereference of a
// pointer to a polymorphic class)
}
Output (exact output varies by system):
Person
Employee
Person*
Employee