Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Apr 16, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.h
class base{
	virtual ~base();

class derived : public base
	virtual ~derived();

//file: RTTIdemo.cpp
#include <typeinfo>
#include <iostream>
#include "classes.h"

using namespace std;

void identify(base & b) { //a demonstartion of RTTI

if ( typeid(b) == typeid(base))
cout<<"base object received" <<endl;
else 	//an object derived from base 
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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date