Professional Documents
Culture Documents
about an object's data type at runtime. This information is typically stored as part of
an object's class hierarchy, and it allows programs to determine the type of an object
even if the type of the object is not known at compile-time. RTTI enables a number
of important programming techniques, including dynamic dispatch, dynamic casting,
and reflection.
RTTI was added to the C++ language because many vendors of class libraries were
implementing this functionality themselves. This caused incompatibilities between
libraries. Thus, it became obvious that support for run-time type information was
needed at the language level.
For the sake of clarity, this discussion of RTTI is almost completely restricted to
pointers. However, the concepts discussed also apply to references.
There are three main C++ language elements to run-time type information:
typeid is an operator in C++ that provides information about an object's data type
at runtime. It is part of the RTTI (Runtime Type Information) mechanism in C++.
class Shape {
public:
virtual ~Shape() {}
};
int main() {
Shape *shape = new Circle;
std::cout << "The type of the shape is: " << typeid(*shape).name() <<
std::endl;
return 0;
}
Dynamic casting is a mechanism in C++ that allows you to cast a pointer or reference
from one type to another type, where the target type is not known until runtime. This
is often used in object-oriented programming when you have a base class pointer
that needs to be cast to a derived class pointer. Dynamic casting is implemented
using RTTI (Runtime Type Information).
class Shape {
public:
virtual ~Shape() {}
};
int main() {
Shape *shape = new Circle;
Circle *circle = dynamic_cast<Circle*>(shape);
if (circle) {
std::cout << "The shape is a Circle." << std::endl;
} else {
std::cout << "The shape is not a Circle." << std::endl;
}
return 0;
}
In this example, we have a base class Shape and two derived classes, Circle and
Square. In main(), we create a pointer to a Shape object and assign it to a new Circle
object. We then use the dynamic_cast operator to cast the shape pointer to a Circle*
pointer. If the cast is successful, the circle pointer will point to the Circle object, and
the output will be The shape is a Circle.. If the cast is not successful, the circle pointer
will be nullptr, and the output will be The shape is not a Circle.
Runtime error
The shape is not a Circle.
The shape is a Circle.
None of these.
Close