Downcasting in C++

downcasting

Downcasting in C++

Downcasting is a process of converting a base class reference to a derived class reference

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
  • Using these pointer  call parent and child methods

Example program to demonstrate downcasting in C++

#include
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();
}

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