devxlogo

Retrieving actual object type in run-time

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.
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist