Upcasting in C++

Upcasting in C++

Upcasting allows public inheritance without the need of an explicit type cast

Definition: Upcasting is a process of converting the derived class pointer to base class pointer so that anything that we can do on the base object can also be done on the derived class object

Both upcasting and downcasting gives it possible to write  complex programs with a simple syntax

Steps in upcasting

  • Create parent class pointer
  • Create an object for child class
  • Assign the address of the child object (reference) the parent class pointer
  • Invoke methods using child object
Upcasting

Example program to demonstrate upcasting 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 show()
{
cout << "Derived Class\n";
}
};

int main()
{
parent* p; //Base class pointer
child c; //Derived class object
p = &c;//assign child reference to parent class pointer
c.show(); //Late Binding Ocuurs
p->show();
}

O/P

Derived class 
Base class

Upcasting allows treating a derived type as if it was its base type i.e  any changes made on derived will also show an effect on the base  class

If you do upcasting you can call only access those properties that are inherited or overridden from base class,child class properties cannot be accessible

Please Login/Signup to comment