This is one of the most important casting operators. The “dynamic_cast” performs a run-time type casting which also checks the type casting validity. If type casting is done to compatible type then it succeeds else it will throw “bad_cast” exception.
Normal syntax to do dynamic_cast is as follows:
dynamic_cast <target-type> (expr)
where target-type and expr must be of type pointer or reference.
Important Points
- dynamic_cast mainly used on polymorphic type of casting.
- Target-type and expr must be a pointer or reference.
- dynamic_cast is not possible to cast one type of template pointer to another type of template pointer.
Let’s have a look at the sample program to understand dynamic_cast operator functionality.
#include <iostream>
using namespace std;
class Base
{
public:
int m;
Base (int x): m (x)
{
cout << "Inside Base::Base ()" << endl;
}
virtual int get ()
{
cout << "Inside Base::get ()" << endl;
return m;
}
virtual void set (int a)
{
cout << "Inside Base::set ()" << endl;
m = a;
}
};
class Derived: public Base
{
public:
Derived (int m): Base (m)
{
cout << "Inside Derived::Derived ()" << endl;
}
int get ()
{
cout << "Inside Derived::get ()" << endl;
return m;
}
void set (int a)
{
cout << "Inside Derived::set ()" << endl;
m = a;
}
};
template <class T>
class NUM
{
public:
void demo ()
{
cout << "Inside NUM" << endl;
}
};
template <class T>
class SQR_NUM: public NUM <T>
{
public:
void demo ()
{
cout << "Inside SQR_NUM" << endl;
}
};
int main ()
{
Base *bp;
Derived *dp;
bp = new Derived (10);
bp -> get ();
dp = dynamic_cast <Derived *> (bp);
if (dp)
{
cout << "dynamic_cast Type casting works !!!" << endl;
dp -> get ();
}
delete bp;
SQR_NUM <int> *sq;
NUM <int> *num;
SQR_NUM <int> x;
NUM <int> y;
SQR_NUM <double> z;
/* Note here that dynamic_case is not applicable for one type of template pointer to another*/
num = dynamic_cast <SQR_NUM <int> *> (&x);
if (num) {
cout << "Cast from SQR_NUM to NUM is OK!!" << endl;
num -> demo ();
} else {
cout << "Cast from SQR_NUM to NUM is NOT OK!!" << endl;
}
}
Let’s analyze the output of above program.
Inside Base::Base ()
Inside Derived::Derived ()
Inside Derived::get ()
dynamic_cast Type casting works !!!
Inside Derived::get ()
Cast from SQR_NUM to NUM is OK!!
Inside NUM