Downcasting is a process of converting a base class reference to a derived class reference Here we would learn about downcasting in C++ which includes steps in downcasting and examples to help you learn easily and showing you how to implement downcasting.
What is Downcasting in C++?
The Downcasting is an opposite process to the upcasting, which converts the base class’s pointer or reference to the derived class’s pointer or reference. It manually cast the base class’s object to the derived class’s object, so we must specify the explicit typecast. The downcasting does not follow the is- a relation in most of the cases. It is not safe as upcasting. Furthermore, the derived class can add new functionality such as; new data members and class member’s functions that use these data members.
Steps in downcasting
Create objects for parent and child class
Create child class pointer and assign child reference with explicit typecasting
#include <iostream>
using namespace std;
class parent //parent class
{
public:
void show()
{
cout << "Base class\n";
}
};
class child:public parent //child class
{
public:
void display()
{
cout << "Derived Class\n"; } }; int main() { parent p; child c; parent *ptr1 = &c; //impilict type casting allowed child *ptr2 = (child*)&c; //requires explicit cast //upcasting is safe ptr1->show();
ptr2->display();
//downcasting is unsafe
ptr2->show();
return 0;
}
Output
Base class
Derived class
Base class
Downcasting requires an explicit type conversion because a derived class adds new data members and a class member functions that use this data member wouldn’t be applied to the base class
Downcasting is not as safe as upcasting because the derived class object can be always treated as the base class object its vice versa is not right, you will get access to the memory that does not have any information of the derived class object .this is the danger with downcasting
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment