C++ Programming Guide | ![]() ![]() ![]() ![]() ![]() |
Runtime Type Identification
This chapter explains the use of Runtime Type Identification (RTTI). Use this feature while a program is running to find out type information that you could not determine at compile time.
6.1 Static and Dynamic Types
In C++, pointers to classes have a static type, the type written in the pointer declaration, and a dynamic type, which is determined by the actual type referenced. The dynamic type of the object could be any class type derived from the static type. In the following example,
ap
has the static typeA*
and a dynamic typeB*
.
class A {};class B: public A {};extern B bv;extern A* ap = &bv;RTTI allows the programmer to determine the dynamic type of the pointer.
6.2 RTTI Options
In compatibility mode (
-compat[=4]
), RTTI support requires significant resources to implement. RTTI is disabled by default in that mode. To enable RTTI implementation and recognition of the associatedtypeid
keyword, use the option-features=rtti
. To disable RTTI implementation and recognition of the associatedtypeid
keyword, use the option--features=no%rtti
(the default).In standard mode (the default mode), RTTI does not have a significant impact on program compilation or execution. RTTI is always enabled in standard mode.
6.3
typeid
OperatorThe
typeid
operator produces a reference to an object of classtype_info
, which describes the most-derived type of the object. To make use of thetypeid()
function, the source code must#include
the<typeinfo>
header file. The primary value of this operator and class combination is in comparisons. In such comparisons, the top-levelconst
andvolatile
qualifiers are ignored, as in the following example. Note that, in this example,A
andB
are types which have default constructors.
The
typeid
operator throws abad_typeid
exception when given a null pointer.6.4
type_info
ClassThe class
type_info
describes type information generated by thetypeid
operator. The primary functions provided bytype_info
are equality, inequality,before
andname
. From<typeinfo.h>
, the definition is:
The
before
function compares two types relative to their implementation-dependent collation order. Thename
function returns an implementation-defined, null-terminated, multibyte string, suitable for conversion and display.The constructor is a private member function, so you cannot create a variable of type
type_info
. The only source oftype_info
objects is in thetypeid
operator.
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |