“dynamic_cast” is new concept in C++ 11.
dynamic_cast is used at runtime to check the correctness of down casting.
As it checks the correctness at runtime, it is slower than “static_cast”.
“dynamic_cast” is used in handling polymorphism.
“dynamic_cast” will return the object if the cast is correct else it will return NULL.
Note:
There should be atleast 1 virtual function for “dynamic_cast” to work.
Consider below scenario where “dynamic_cast” is useful:
There is a Base class and 2 derived classes D1 and D2.
Now we have upcasted the derived class D1 object to base class pointer and then downcasted that base pointer to derived class 2 object. This is an error, you cannot do it. As both of the object belongs to 2 different objects.
Syntax of dynamic_cast cast:
data_type *var_name = dynamic_cast <data_type *>(pointer_variable);
Example:
#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;
class Base
{
public:
virtual void print()
{
}
};
class Derived_1: public Base
{
};
class Derived_2: public Base
{
};
int main(void)
{
Derived_1 d1;
Base *bp = dynamic_cast<Base*> (&d1);
Derived_2 *d2 = dynamic_cast<Derived_2*> (bp);
if(d2 == nullptr)
{
cout<<"Casting did not occur"<<endl;
}
else
{
cout<<"Casting occur"<<endl;
}
return 0;
}
Output:
Casting did not occur
Note:
dynamic_cast is used with pointer and reference to object only.
RTTI: Runtime Tyoe Information:
C++ has given a standard wat to determine the type of object at runtime.
RTTI can be found by using 2 operations:
1. typeid(variable).name()
2. dynamic_cast