Downcasting in C++

Downcasting in C++

Both upcasting and downcasting helps  to write  complex programs with a simple syntax

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

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
Downcasting

Example program to demonstrate downcasting in C++

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

O/P

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