The C & C++ Typecasting: Retrieving 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++ run time type information using typeid() method for the class object

To show: How to retrieve the C++ run time type information (RTTI) using typeid() method

 

 

// Getting the run time type information

#include <iostream>

#include <typeinfo>

using namespace std;

 

// polymorphic base class...

class __rtti Test

{

// This makes Test a polymorphic class type.

virtual void func() {};

};

 

// derived class

class Derived : public Test {};

 

int main(void)

{

// Instantiate Derived type object

Derived DerivedObj;

// Declare a Derived type pointer

Derived *DerivedPtr;

// Initialize the pointer

DerivedPtr = &DerivedObj;

 

// do the run time checking

if(typeid(*DerivedPtr) == typeid(Derived))

// check the type of *DerivedPtr

cout<<"Ptr *DerivedPtr type name is "<<typeid(*DerivedPtr).name();

 

if(typeid(*DerivedPtr) != typeid(Test))

cout<<"\nPointer DerivedPtr is not a Test class type.\n";

return 0;

}

 

Output example:

 

You may continue your debug though there are errors.

 

c and f are different type.

int before double: 1

double before int: 0

class A before class B: 1

Press any key to continue . . .

 

 

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