C++ Runtime Type Identification(RTTI)

What is RTTI for?

The intent of RTTI is to provide a standard way for a program to determine the type of object during runtime.

How Does RTTI Work?

  • The dynamic_cast operator generates a pointer to a derived type from a pointer to a base type, if possible. Otherwise, the operator returns 0, the null pointer.
  • The typeid operator returns a value identifying the exact type of an object.
  • A type_info structure holds information about a particular type.

Caution

RTTI works only for classes that have virtual functions.

class Grand{has virtual methods};
class Superb: public Grand{...};
class Magnificent : public Superb{...};

Grand* pg = new Grand;
Superb * pm = dynamic_cast<Superb *>(pg); 
// This code asks whether the pointer pg can be type cast safely to the type Superb*. If it can, the operator renturns the address of the object. Otherwise it returns 0, the null pointer. 


You can invoke the Say() function safely:

if(ps = dynamic_cast<Superb *>(pg))
    ps->Say();

The typeid operator and type_info Class

The typeid operator returns a reference to a type_info object, where type_info is a class defined in the typeinfo header file (formerly typeinfo.h). The type_info class overloads the == and != operators so that you can use these operators to compare types.
For example, the following expression evalluates to the bool value true if
pg points to a magnificent object and to false otherwise:

typeid(Magnificent) == typeid(*pg);
// if pg happens to be a null pointer, the program throws a bad_typeid exception.

cout<< typeid(*pg).name() <<"\n";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值