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:
- 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.
- In order to enable RTTI support, an object must have at least one virtual member function.
- Comparing to static (i.e., compile-time) type information, RTTI incurs a performance penalty, so you consider that when performance matters.
- 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.