Cpp Tutorial: Upcasting and downcasting in C++

Upcasting: It is the process of converting derived-class reference or pointer to the base class.

Downcasting: It is the process of converting base-class reference or pointer to the derived class.

Upcasting:

Here the derived class pointer is converted to base class.
This is allowed in inheritance.
There is no need of explicit typecasting.
There is an is-a relationship between the base class and derived class.
Object-slicing can occur in upcasting.

Example of upcasting:

#include <iostream>       // std::cout

// for more tutorials visit www.ProDeveloperTutorial.com

using namespace std;

class Base 
{
public:
  void baseFun() 
  {
      cout<<"Base Function"<<endl;
  }
};

class Derived: public Base 
{
public:
  void derivedFun()
  {
      cout<<"Derived Fun"<<endl;
  }
};

int main( ) 
{ 
  Derived dObj;
    
  //upcasting - implicit upcasting is allowed
  Base *bPtr = &dObj; 

  bPtr -> baseFun();

  return 0; 
}

Output:

Base Function

Downcasting:

It converts base class pointer to derived class pointer.
You need to explicitly type cast during downcasting.

#include <iostream>       // std::cout

// for more tutorials visit www.ProDeveloperTutorial.com

using namespace std;

class Base 
{
public:
  void baseFun() 
  {
      cout<<"Base Function"<<endl;
  }
};

class Derived: public Base 
{
public:
  void derivedFun()
  {
      cout<<"Derived Fun"<<endl;
  }
};

int main( ) 
{ 
  Base bObj;

  // explicit type cast is required
  Derived *dPtr =  (Derived *) &bObj;
  dPtr -> derivedFun();
    
  return 0; 
}

Output:

Derived Fun
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *