{steinsoft.net}
 
 
 
 
 
Home/News
Code Snippets
Board
Projects
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Leipzig
Home :: Programming :: Code Snippets :: Cpp :: Dynamic Type Information

[ Dynamic Type Information ]

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!

 Last edited 2002-12-08 23:31:59 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0