Submitted by: mohit12379
Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves. This caused incompatibilities between libraries. Thus, it became obvious that support for run-time type information was needed at the language level.
There are three main C++ language elements to run-time type information:
1)The dynamic_cast operator. :- Used for conversion of polymorphic types.
class B { ... };
class C : public B { ... };
class D : public C { ... };
void f(D* pd)
{
C* pc = dynamic_cast<C*>(pd);// ok: C is a direct base class
// pc points to C subobject of pd
B* pb = dynamic_cast<B*>(pd);// ok: B is an indirect base class
// pb points to B subobject of pd
...
}
---------------------------------------------------------------------------
2)The typeid operator :- Used for identifying the exact type of an object.
3)The type_info class :- Used to hold the type information returned by the typeid operator.
The type_info class describes type information generated within the
program by the compiler.
NOTE:- TRY THIS EXAMPLE IS COMPILE AND LINK USING MSVC++ 6.0 CL.EXE Compiler and Linker PLS CHECK SAME typid available in UNIX based C++;
**************************************************************************************
#include "stdio.h"
#include <typeinfo.h>
class A
{
public:
};
class B:public A
{
public:
};
int main(int argc, char* argv[])
{
int iVal = int();
float fVal = float();
char cVal = char();
A a,a1;
B b;
const type_info& t_iVal = typeid(iVal); // Holds Simple int DataType Info
const type_info& t_iValRef = typeid(&iVal); // Holds pointer type_info
printf("\n Type Info of iVal = %s\n",t_iVal.name());
printf("\n Type Info of &iVal = %s\n",t_iValRef.name());
printf("\n Type Info of fVal = %s\n",typeid(fVal).name());
printf("\n Type Info of &fVal = %s\n",typeid(&fVal).name());
printf("\n Type Info of cVal = %s\n",typeid(cVal).name());
printf("\n Type Info of &cVal = %s\n\n",typeid(&cVal).name());
printf("\n Type Info of a = %s\n",typeid(a).name());
printf("\n Type Info of b = %s\n\n",typeid(b).name());
if(typeid(a) == typeid(a1))
{
printf("\n BOTH INSTANCES a AND a1 BELONGS TO SAME CLASS \n\n");
}
return 0;
}
****************************************************************************
PLS ANY DOUBT WRITE ME AT mohit.gonduley@gmail.com
Above answer was rated as good by the following members:
wael.salman