Dynamic Cast

This is one of the type casting provided by C++. Let us understand with the help of an example.

#include <iostream>
using namespace std;
#define MAX_LENGTH 50
class person {
unsigned int m_age;
char m_name[MAX_LENGTH];
public:
person(unsigned int age, char* name) {
m_age = age;
    int len = strlen(name);
strncpy(m_name, name, len);
m_name[len+1] = ‘\0’;
}
virtual ~person(){}
};

class student : public person {
unsigned int m_rollNumber;
public:
student(unsigned int age, char* name, unsigned int
rollNumber):person(age, name),m_rollNumber(rollNumber) {
}
~student(){}
};

class teacher: public person {
unsigned int m_salary;
public:
teacher(unsigned int age, char* name, unsigned int
salary):person(age, name),m_salary(salary) {
}
~teacher(){}
};

int main() {
person* p1 = new student(15, “Atul”, 42);
person* p2 = new teacher(35, “Mohan”, 20000);
delete p1;
delete p2;
return 0;
}

In the main function, you can see that Student address is assign to p1 and similarly for teacher. This is called upcasting and it is safe since student is clearly derived from person i.e. there is no type casting required for upcasting.

Let us say we have to convert p1 in to student. However, person can be a student or teacher. Therefore, it is not possible to determine the exact derived object without the cast. For this, C++ provide dynamic cast.  The process of determining the exact derived class Object from base class object is called downcasting.

student* s = dynamic_cast<student*>(p1);
if (NULL != s) { // Success
    cout << “Success: student object” << endl;
}

teacher* t= dynamic_cast<teacher*>(p1);
if (NULL != t) {  //Failed
    cout << “Won’t Enter here: not a teacher object” << endl;
}

dynamic_cast return the pointer to the desired type if the cast is proper and successful otherwise it return NULL to indicate that dynamic_cast failed. That is why in the above code snippet if check is added to check the return value.

dynamic_cast must be used only when the polymorphic inheritance is involved because dynamic_cast uses VTABLE information to find out the exact type. In the above classes, we have use virtual destructor in the base class and this make all the classes polymorphic in nature.

dynamic_cast requires overhead to determine the exact the desired type so if dynamic_cast is getting used a lot, then we can use the static_cast instead. But static_cast should be used if you know the exact target type.

static_cast does not allow to type case outside the inheritance so in that way, it is safer but still it is only recommended to use static_cast instead of dynamic_cast when there is need of it in lot of places in the code.

Related posts