Thursday, March 08, 2007

RTTI

Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution.

There are three main C++ language elements to run-time type information:

The dynamic_cast operator - Used for conversion of polymorphic types.

The typeid operator - Used for identifying the exact type of an object.

The type_info class - Used to hold the type information returned by the typeid operator.

The typeid operator allows the type of an object to be determined at run time.

The result of typeid is a const type_info&.


we faced the problem like this to idenify the class object type at run time...

if we follow MFC, we need to create Shape class as a derived class

of CObject In order to access the MFC RTTI.

Instead of it we are using simple C++ RTTI.

Here it is the sample code...




#include
#include
# include
# include

// compile with: /GR /EHsc

class Shape
{
public:
virtual void draw() {}
};

class CLine : public Shape
{
void draw()
{
cout<<"CLine Class";
}
};
class CRectangle : public Shape
{
void draw()
{
cout<<"CRect Class";
}
};

using namespace std;
void main()
{

Shape *Sh = new CRectangle();
int r=0;
char DebugString[100];

sprintf(DebugString,"%s",typeid( *Sh ).name());

if(strcmp(DebugString,"Class CRectangle") == 0)

{
cout << "we are using Rectangle object";
}

Shape* h = new CLine();

sprintf(DebugString,"%s",typeid( *h ).name());


if(strcmp(DebugString,"Class CLine") == 0)
{
cout<< "we are using Line Object";

}


}

No comments: