What is runtime type control in C++?
Run-time type identification (RTTI) lets you find the exact type of an object when you have only a pointer or reference to the base type. This can be thought of as a “secondary” feature in C++, a pragmatism to help out when you get into messy situations.
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object's data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution.
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.
RTTI, Run-Time Type Information, introduces a [mild] form of reflection for C++. It allows to know for example the type of a super class, hence allowing to handle an heterogeneous collection of objects which are all derived from the same base type. in ways that are specific to the individual super-classes.
It enables you to identify the dynamic type of a object at run time. For example:
class A
{
virtual ~A();
};
class B : public A
{
}
void f(A* p)
{
//b will be non-NULL only if dynamic_cast succeeds
B* b = dynamic_cast<B*>(p);
if(b) //Type of the object is B
{
}
else //type is A
{
}
}
int main()
{
A a;
B b;
f(&a);
f(&b);
}
It is not just about dynamic_cast, but the entire RTTI is part of it. The best place to learn about RTTI is section 15.4 of the C++ Programming Language by Bjarne Stroustrup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With