Typeid
Encyclopedia : T : TY : TYP : Typeid
In C++, the
typeid keyword is used to determine the class of an object at runtime. According to the C++ specification, it returns a reference to typeinfo. As such, modern compilers will not let you assign the return value of typeid to a local variable, as the constructor for typeinfo is private. Using the name member function of typeinfo is a sufficient general workaround for situations which require one to store the class type. typeid is often preferred to dynamic_cast<class_type> in situations where just the class information is needed, because typeid is a constant-time procedure, whereas dynamic_cast must traverse the class derivation lattice of its argument at runtime.Examples
Supposing that you had class "Message" a derived class "FatMessage":...
class Message ;..., and the following code:class FatMessage : public Message ;
Message *n = new Message(); Message *p = new FatMessage(); string wakka = typeid(*n).name();cout << typeid(*p) << endl; cout << typeid(p) << endl; cout << wakka << endl;
Then, typeid would return the following results in code compiled with RTTI:
FatMessage Message MessageImportant: Note that you had to dereference the pointer in the first cout.
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
