Upcasting in C++ with Simple Example


If a base class pointer contains the address of a derived class object, then the pointer is called as Upcasted pointer & this process is called as Upcasting. Let us look at a program to understand the concept of upcasting.

C++ Program For Upcasting in C++

#include<iostream> using namespace std; class base{ public: void display1(){ cout<<"base - display1 \n"; } void display2(){ cout<<"base - display2 \n"; } }; class der : public base{ public: void display1(){ cout<<"der - display1 \n"; } void display2(){ cout<<"der - display2 \n"; } }; int main(){ base b, *bptr; bptr = &b; bptr->display1(); bptr->display2(); der d; bptr = &d; //upcasting bptr->display1(); bptr->display2(); return 0; }

Output:-

base - display1
base - display2
base - display1
base - display2

Explanation of the program

We have assigned the address of a derived class object to the base class pointer. Is this not an error, since we are assigning of one type to a pointer of another? No, the rule is that derived object can be treated as a base object as well since derived object contains base part. So, in this case, the compiler relaxes the type checking. Note that we have used the following statement.

bptr->display1();

First, when bptr points to the base object (b) and second, when bptr points to the derived object (d). However, both the times, it executed base::display1() function. This is because the Compiler ignores the contents of the pointer bptr & chooses the member function that matches the type of the pointer. Here, since bptr's type matches the base class, the display1() of base class gets called. Same thing happens when we call display2().