Dynamic_Cast Operator in C++

How is dynamic_cast operator used in C++?
What is RTTI Information?


Dynamic_Cast Operator is used with pointers and objects to do casting at the runtime unlike other cast operators. In order for this operation, the typeid operator or exceptions to work in C++, Run-Time Type Information (RTTI) must be enabled.

Example :

#include <iostream.h> using namespace std;
struct X
virtual ~X() { };
}; struct Y : X { };
int main()
Y a;
X * ptr1 = &a;
void * ptr2 = dynamic_cast(ptr1);
cout << "Address of ptr2:" << ptr2 << endl;
cout << "Address of a:" << &a << endl;

Result :

Address of ptr2: 0012FF88
Address of a: 0012FF88

In the above example the dynamic_cast operator is used on a "ptr1", so that the address of the object "a" is assigned to "ptr2" at the runtime.

This operator is a part of Run-Time Type Information (RTTI).

C++ Tutorial

Ask Questions

Ask Question