Retrieving actual object type in run-time

C++ supports Run-time Type Identification (RTTI), which enables detection of actual object type during program execution using the built-in typeid() operator. Here is an example:

 //file: classes.hclass base{	base();	virtual ~base();};class derived : public base	{	derived();	virtual ~derived();};//file: RTTIdemo.cpp#include #include #include "classes.h"using namespace std;void identify(base & b) { //a demonstartion of RTTIif ( typeid(b) == typeid(base))cout<<"base object received" <

When using typeid(), and RTTI in general, please keep in mind the following:

  1. typeid() may take either an object or a type-name as its argument and return a const object of type typeinfo containing all necessary type information.
  2. In order to enable RTTI support, an object must have at least one virtual member function.
  3. Comparing to static (i.e., compile-time) type information, RTTI incurs a performance penalty, so you consider that when performance matters.
  4. In most cases, the use of typeid() is not required and even not recommended. Note that a virtual member function like name() could have achieved the same effect more easily.
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: