FAQ 27.20 What does typeid() do?

FAQ 27.20 What does typeid() do?

graphics/new_icon.gif

It determines the precise type of an object at runtime.

Given a reference or pointer as input, typeid() returns a reference to a standard library class called type_info. type_info has a name() member function that returns the name of the parameter's type in an implementation-specific format. This name represents the precise, lowest-level type of the object. If the value of the pointer is NULL, typeid() throws a bad_typeid exception.

Note that dynamic_cast<T>(p) and static_cast<T>(p) are template functions, where T is the template parameter and p is the function parameter, but typeid() is not a template function.

typeid() and dynamic_cast<T>() are two sides of the same coin. They both take a base class pointer or reference that may refer to a derived class object. But typeid() returns a class name whereas dynamic_cast<T>() is passed a class name. typeid() is used to discover the object's exact class, but it doesn't convert the pointer; dynamic_cast<T>() converts the pointer but doesn't determine the object's exact class the pointer may be converted to some intermediate base class rather than to the object's exact class.

The character representation of the class name from name() is stored in system memory and must not be deleted by the programmer.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net