This snippet will show you how to get type information of an instance in your code at runtime. You will be able to know the name of the type of a variable.
The operator you need is typeid(expression). expression is a variable you want to get information about. typeid will return a constant reference to a type_info object that holds info about the given instance. Here's the definition:
class type_info { public: virtual ~type_info(); int operator==(const type_info& rhs) const; int operator!=(const type_info& rhs) const; int before(const type_info& rhs) const; const char* name() const; const char* raw_name() const; private: ... };
Remember that you have to include typeinfo.h before using typeid/type_info. Using this operator is very easy. The class type_info also supports comparison so you can compare two variables dynamically. You could check whether they have the same type or not.
Here is a little example how to use it:
#include <iostream.h> #include <typeinfo.h> //any user class #include "MyClass.h" int main() { char test; char test2; MyClass myClass; cout << "Type of test: " << typeid(test).name() << endl; cout << "Type of test and test2 are the same: " << (typeid(test) == typeid(test2)) << endl; cout << "Dynamic type name of myClass: " << typeid(myClass).name() << endl; return 0; }
Output of this application:
Type of test: char Type of test and test2 are the same: 1 Dynamic type name of myClass: class MyClass
Not very difficult, isn't? This operator works for everything, for pointers, references.. If you have problems, m@il me. Happy Coding!