Using the typeid().name() method for the C++ run time type information (RTTI)

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Retrieving the C++ class object type information using typeid().name() method

To show: The C++ run time type information (RTTI) - using typeid().name() method

 

// run time type information

#include <iostream>

#include <typeinfo>

using namespace std;

 

class Base

{

public:

virtual void funct(){}

};

 

class Derived:public Base{};

 

int main(void)

{

Derived* Test1 = new Derived;

Base* Test2 = Test1;

 

cout<<"The type name of Test1 is: ";

cout<<typeid(Test1).name()<<endl;

cout<<"The type name of *Test1 is: ";

cout<<typeid(*Test1).name()<<endl;

cout<<"The type name of Test2 is: ";

cout<<typeid(Test2).name()<<endl;

cout<<"The type name of *Test2 is: ";

cout<<typeid(*Test2).name()<<endl;

delete Test1;

 

return 0;

}

 

Output example:

 

The type name of Test1 is: class Derived *

The type name of *Test1 is: class Derived

The type name of Test2 is: class Base *

The type name of *Test2 is: class Derived

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index