Upcasting and Downcasting in C++

In this tutorial, we will learn about upcasting and downcasting in C++.

Upcasting and downcasting are an important part of C++ and enable the possibility of object-oriented programming, following polymorphism property. Polymorphism occurs when there is an inheritance of classes. A base class is a parent class and its children are known as derived classes. With C++, we can have a derived class pointer to behave as a base class pointer. This is upcasting.
Downcasting is an opposite process, where the base class pointer is made to behave as a derived class pointer.

Upcasting in C++

Upcasting, as described above, is converting a derived class pointer to a base class pointer. It is allowed for public inheritance. This is because of the is-a relationship between the parent and the child class. An example is as shown:

#include<bits/stdc++.h>
using namespace std;
class Employee {
int id;
string name;
int salary;
public:
Employee(int eno, string ename, double esalary) {
id=eno;
name=ename;
salary=esalary;
}
};

class worker : public Employee {
public:
worker(int i, string n, int s, int h, int r):Employee(eno,ename,esalary)
{
hours=h;
rate=r; 
};

int main()
{
Employee *eptr;
worker *weptr;
Employee e1(1, "Tushar", 100000);
worker w1(12, "Gautam", 12000, 10, 1000);
eptr = &w1;
cout<<e1->ename;
cout<<e1->hours;
return 0;
}
Output:
Tushar
10

Explanation

  • In the code above, two classes are declared, named Employee(parent class) and worker(child class).
  • A few arguments are being passed to the respective classes.
  • Shifting focus on main function, a pointer to Employee class is created and the class objects are given with required parameters.
  • After declaration, upcasting is done by assigning the worker class pointer to Employee class pointer.
  • With Employee class pointer, the address of worker class can be held and we can access the worker class.
  • Important to note here that we have object slicing – when the derived class object is assigned to the base class object, then extra attributes from the derived class object are removed from the object.

Downcasting in C++

Downcasting is the opposite of upcasting. From the code above, a class pointer is defined for the child class as well. We will explain downcasting from the same code. We have to explicitly specify downcast.

//same code as above

int main()
{
Employee *eptr;
worker *wptr;
Employee e1(1, "Tushar", 100000);
worker w1(12, "Gautam", 12000, 10, 1000); 
weptr = &e1;
cout<<e1->ename; 
cout<<e1->hours; 
return 0;
}

This will throw a compiler error as the e1 object is not from the class worker or any class inheriting from it. It belongs to the parent class. Thus, we can conclude that the derived class pointer cannot hold the address of the base class object.

Leave a Reply

Your email address will not be published.