Upcasting in C++

Upcasting in C++ img

Upcasting

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

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

Upcasting in C++

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 in C++

Example program to demonstrate upcasting in C ++

Run

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

return 0;
}

Output

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 to those properties that are inherited or overridden from base class, child class properties cannot be accessible.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription