Describe RTTI – Run Time Type Information in C++

Answer: RTTI – Run Time Type Information in C++ is a mechanism that allows the type of an object to be determined at run time.

dynamic_cast operator and typeid operator are part of RTTI – Run time type identification in C++.

  • dynamic_cast : Used for type conversion of polymorphic types.
  • typeid operator: Used for identifying the exact type of an object.

[ Recommned: Use of RTTI – Dynamic_cast in C++]

RTTI in C++ is available only for classes which are polymorphic which means classes have at least one virtual method.

NOTE: Since RTTI is included in the virtual method table i.e. VTABLE, there should be at least one virtual function. In fact, if we have at least one virtual method in a class, VTABLE will get generated.

If we apply RTTI on non-polymorphic class in c++, compiler will flash an error. Consider below example of dynamic_cast on non-polymorphic classes.

/Dynamic_cast works on Polymorphic classes only/

//Check if dynamic cast apply on polymorphic class only. i.e class contains virtual function

class B {
public:
	void func()
	{
		cout << "Class B : base func" << endl;
	}
  
};

class D: public B{
public:

  	void func()
	{
		 cout << "Class D Der func" << endl;
	}
};

int main(){
  D dObj;
  B *bp=&dObj;
  D *dp= dynamic_cast<D*>(bp);// Error 1	error C2683: 'dynamic_cast' : 'B' //is not a polymorphic type		
  dp->func();
 
  return 0;
}

Related Posts