Reputation: 1187
I'm just trying to understand the down casting in more details, I understand that it is not advisable as it leads to undefined run time behavior. When do we really need to use down casting?
Also consider the coding snippet and the dynamic_cast returns for the down casting but when I use reinterpret_cast it prints out the derived class function rightly, how? The object slicing will take in place only when assigning objects by value but not by reference or pointers?
#include <iostream>
using namespace std;
class base
{
public:
void func1()
{
std::cout<<"\n Base Function"<<std::endl;
}
virtual ~base(){cout<<"\n Base Destructor"<<endl;}
};
class derived:public base
{
public:
void func2()
{
std::cout<<"\n Derived Function"<<std::endl;
}
};
int main()
{
base *ptr = dynamic_cast<base*>(new derived); // Up casting
if (ptr)
{
ptr->func1();
}
else
{
cout<<"\n casting failed"<<endl;
}
derived *ptr1 = dynamic_cast<derived*>(new base); // Down casting
if (ptr1)
{
ptr1->func2();
}
else
{
cout<<"\n ptr1 casting failed"<<endl;
}
return 0;
}
Upvotes: 1
Views: 2485
Reputation: 1056
A downcasting by itself does not lead to undefined behavior. If you have a pointer or reference to base, you can use a dynamic_cast and be sure that it will only work if it really is a derived. If it is not a derived you will get a nullptr or an exception (when casting a reference). Everything will be checked at runtime.
If you already know that your base pointer is a derived, you could use a static_cast instead. However no checks will be performed so that you can cause undefined behavior of your base pointer is not a derived.
The reinterpret_cast should not be used for downcasting. As with static_cast, no runtime check will be performed, but also no compile-time check is done. You could accidentally cast across inheritance trees (e.g. from base to other_base). For the case of single inheritance, reinterpret_cast will work like a static_cast, but when multiple inheritance is used, reinterpret_cast will not modify the pointer to the correct base inside the object and you have undefined behaviour.
I would recommend to stay away from reinterpret_cast when you can use static_cast instead.
Upvotes: 6