×
>
<

Aptitude

Upcasting and DownCasting in C++

What is Upcasting and Downcasting in C++

In C++ we can create a pointer references between the parent and child classes and form a β€œis aβ€? relation between them. There are two types of casting that can be done –

  • Upcasting
  • Downcasting

Upcasting

In simple terms using upcasting allows us to treat the child class object as if it were the parent class object. There are two ways of creating upcasting relationship –

Way 1

Creating parent class pointer and assigning it to the base classes reference.

Example
  
Parent* parentObj; // Parent class pointer 
Child childObj; // Creating child class object
parentObj = &childObj; // assigning to address reference of base class object
  
Way 1

Creating Parent Classes referenced object and assigning it to the child class object

Example
  
Parent &parentObj; // Parent class reference 
Child childObj; // Creating child class object
parentObj = childObj; // direct assignment
  

Facts

The object is not changing

However, even with the child class objects we will only be able to access the data and function members of the parent class

  
#include 
using namespace std;

// This is Parent class
class Parent
{
  public:
    void print()
    {
      cout << "Parent Class printing" << endl;
    }
};

// This is Child class
class Child : public Parent
{
  public:

  // as we see that it is already declared in the parent function
  void print()
  {
    cout << "Child Class printing" << endl; 
  } 
};

int main() 
{ 
  Parent *parent_object; 
  Child child_object; 
  parent_object = &child_object; 

  // catch of the program is here 
  // also as we are dealing with pointers instead of . we need to use ->
  parent_object->print();

  return 0;
}
  
output
  
Parent Class printing
  
Downcasting

Downcasting is vice versa as of Upcasting. In upcasting we created parent class pointer reference to child class address reference. We can not do this implicitly thus, we follow explicit form, which is –

Example
  
#include 
using namespace std;

// This is Parent class
class Parent
{
public:
void print()
{
cout << "Parent Class printing" << endl;
}
};

// This is Child class
class Child : public Parent
{
public:

// as we see that it is already declared in the parent function
void print()
{
cout << "Child Class printing" << endl; 
} 
};

int main() 
{ 
Parent *parent_object; 
Child *child_object = (Child* ) &parent_object; 
// catch of the program is here 
// also as we are dealing with pointers instead of . we need to use ->
child_object->print();

return 0;
}
  
output
  
Child Class Printing
  

  • In this case even though the final address is of the parent class
  • The function called is of the child class
  • We have to use explicit casting here