In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
,
Object Pascal
Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods.
...
, and
Ada
Ada may refer to:
Places
Africa
* Ada Foah, a town in Ghana
* Ada (Ghana parliament constituency)
* Ada, Osun, a town in Nigeria
Asia
* Ada, Urmia, a village in West Azerbaijan Province, Iran
* Ada, Karaman, a village in Karaman Province, ...
) that exposes information about an object's
data type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
at
runtime. Run-time type information may be available for all types or only to types that explicitly have it (as is the case with Ada). Run-time type information is a specialization of a more general concept called
type introspection
In computing, type introspection is the ability of a program to ''examine'' the type or properties of an object
at runtime.
Some programming languages possess this capability.
Introspection should not be confused with reflection, which goes a st ...
.
In the original C++ design,
Bjarne Stroustrup
Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University ...
did not include run-time type information, because he thought this mechanism was often misused.
Overview
In C++, RTTI can be used to do safe
typecast
In film, television, and theatre, typecasting is the process by which a particular actor becomes strongly identified with a specific character, one or more particular roles, or characters having the same traits or coming from the same social or ...
s, using the
dynamic_cast<>
operator, and to manipulate type information at runtime, using the
typeid
operator and
std::type_info
class. In Object Pascal, RTTI can be used to perform safe type casts with the
as
operator, test the class to which an object belongs with the
is
operator, and manipulate type information at run time with classes contained in the
RTTI
unit (i.e. classes: ''TRttiContext'', ''TRttiInstanceType'', etc.). In Ada, objects of tagged types also store a type tag, which permits the identification of the type of these object at runtime. The
in
operator can be used to test, at runtime, if an object is of a specific type and may be safely converted to it.
RTTI is available only for classes that are
polymorphic, which means they have at least one
virtual method
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part ...
. In practice, this is not a limitation because base classes must have a
virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.
Some compilers have flags to disable RTTI. Using these flags may reduce the overall size of the application, making them especially useful when targeting systems with a limited amount of memory.
C++ – ''typeid''
The
typeid
keyword
Keyword may refer to:
Computing
* Keyword (Internet search), a word or phrase typically used by bloggers or online content creator to rank a web page on a particular topic
* Index term, a term used as a keyword to documents in an information syst ...
is used to determine the
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
of an
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
at
run time
Run(s) or RUN may refer to:
Places
* Run (island), one of the Banda Islands in Indonesia
* Run (stream), a stream in the Dutch province of North Brabant
People
* Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
. It returns a
reference
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
to
std::type_info
object, which exists until the end of the program. The use of
typeid
, in a non-polymorphic context, is often preferred over
dynamic_cast<''class_type''>
in situations where just the class information is needed, because
typeid
is always a
constant-time procedure, whereas
dynamic_cast In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time ty ...
may need to traverse the class derivation lattice of its argument at runtime. Some aspects of the returned object are implementation-defined, such as
std::type_info::name()
, and cannot be relied on across compilers to be consistent.
Objects of class
std::bad_typeid
are thrown when the expression for
typeid
is the result of applying the unary * operator on a
null pointer. Whether an exception is thrown for other null reference arguments is implementation-dependent. In other words, for the exception to be guaranteed, the expression must take the form
typeid(*p)
where
p
is any expression resulting in a null pointer.
Example
#include
#include
class Person ;
class Employee : public Person ;
int main()
Output (exact output varies by system and compiler):
Person
Employee
Person*
Employee
Employee
C++ – ''dynamic_cast'' and Java cast
The
dynamic_cast
operator in
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
is used for
downcasting
In class-based programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.
In many programming languages, it is possible to check through type introspection to determine whether the ...
a reference or pointer to a more specific type in the
class hierarchy
A class hierarchy or inheritance tree in computer science is a classification of object types, denoting objects as the instantiations of classes (class is like a blueprint, the object is what is built from that blueprint) inter-relating the vario ...
. Unlike the
static_cast
In the C++ programming language, static_cast is an operator that performs an explicit type conversion.
Syntax
static_cast (object);
The ''type'' parameter must be a data type to which ''object'' can be converted via a known method, whether ...
, the target of the
dynamic_cast
must be a
pointer or
reference
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
to
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
. Unlike
static_cast
In the C++ programming language, static_cast is an operator that performs an explicit type conversion.
Syntax
static_cast (object);
The ''type'' parameter must be a data type to which ''object'' can be converted via a known method, whether ...
and
C-style typecast (where type check is made during compilation), a type safety check is performed at
runtime. If the types are not compatible, an
exception will be thrown (when dealing with
references
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
) or a
null pointer will be returned (when dealing with
pointers
Pointer may refer to:
Places
* Pointer, Kentucky
* Pointers, New Jersey
* Pointers Airport, Wasco County, Oregon, United States
* The Pointers, a pair of rocks off Antarctica
People with the name
* Pointer (surname), a surname (including a lis ...
).
A
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
typecast behaves similarly; if the object being cast is not actually an instance of the target type, and cannot be converted to one by a language-defined method, an instance of
java.lang.ClassCastException
will be thrown.
Example
Suppose some
function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-oriente ...
takes an
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
of type
A
as its argument, and wishes to perform some additional operation if the object passed is an instance of
B
, a
subclass of
A
. This can be accomplished using
dynamic_cast
as follows.
#include
#include
#include
#include
using namespace std;
class A ;
class B: public A ;
void MyFunction(A& my_a)
int main()
Console output:
Method specific for B was invoked
Method specific for B was invoked
Exception std::bad_cast thrown.
Object is not of type B
A similar version of
MyFunction
can be written with
pointers instead of
references
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
:
void MyFunction(A* my_a)
Delphi / Object Pascal
In Object Pascal, the operator
is
is used to check the type of a class at
run time
Run(s) or RUN may refer to:
Places
* Run (island), one of the Banda Islands in Indonesia
* Run (stream), a stream in the Dutch province of North Brabant
People
* Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
. It tests the belonging of an object to a given class, including classes of individual ancestors present in the inheritance hierarchy tree (e.g. ''Button1'' is a ''TButton'' class that has ancestors: ''TWinControl'' → ''TControl'' → ''TComponent'' → ''TPersistent'' → ''TObject'', where the latter is the ancestor of all classes). The operator
as
is used when an object needs to be treated at run time as if it belonged to an ancestor class.
The RTTI unit is used to manipulate object type information at run time. This unit contains a set of classes that allow you to: get information about an object's class and its ancestors, properties, methods and events, change property values and call methods. The following example shows the use of the RTTI module to obtain information about the class to which an object belongs, creating it, and to call its method. The example assumes that the TSubject class has been declared in a unit named SubjectUnit.
uses
RTTI, SubjectUnit;
procedure WithoutReflection;
var
MySubject: TSubject;
begin
MySubject := TSubject.Create;
try
Subject.Hello;
finally
Subject.Free;
end;
end;
procedure WithReflection;
var
RttiContext: TRttiContext;
RttiType: TRttiInstanceType;
Subject: TObject;
begin
RttiType := RttiContext.FindType('SubjectUnit.TSubject') as TRttiInstanceType;
Subject := RttiType.GetMethod('Create').Invoke(RttiType.MetaclassType, []).AsObject;
try
RttiType.GetMethod('Hello').Invoke(Subject, []);
finally
Subject.Free;
end;
end;
See also
* Type inference
* Type introspection
*
typeof
typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly s ...
*
Reflection (computer science)
In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.
Historical background
The earliest computers were programmed in their native assembly lang ...
*
Template (C++)
Template may refer to:
Tools
* Die (manufacturing), used to cut or shape material
* Mold, in a molding (process), molding process
* Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, sha ...
References
External links
dynamic_cast
operator at IBM Mac OS X Compilersdynamic_cast
operator at MSDN
{{DEFAULTSORT:Run-Time Type Information
Articles with example C++ code
C++
Class (computer programming)
Data types