Upcasting

Process of casting/referring to a derived class object as if it were a base class object. This is possible due to the "is-a" relationship between the base and derived classes, whereby the derived class inherits the public (and protected) members without an explicit type cast. This, in turn, is possible because the derived class object is a type of its base class object.

 

 

Referred to as Upcasting due to UML notation of derived class pointing up to the base class.

 

Achieved by using/converting the address of the derived class object to a base class object.

 

This example shows a DerivedClass object being sent to the function accepting BaseClass types:

#include <iostream>
#include <string>
using namespace std;

class BaseClass {
	public:
		void speak(){
			cout << "BaseClass speak function." << endl ;
		}
};

class DerivedClass : public BaseClass {
	public:
		void speak(){
			cout << "DerivedClass speak function." << endl ;
		}
};

void say(BaseClass & xyz){  //accepting BaseClass type
	xyz.speak() ;
}

int main() {
	DerivedClass myObject ;  //instantiate DerivedClass object

	say(myObject) ;  //send DerivedClass object to function accepting BaseClass type = upcasting

	return 0;
}

Compile & Run:

BaseClass speak function.

 

 

This example shows a DerivedClass object being assigned to a BaseClass pointer, which is then used to invoke the method:

#include <iostream>
#include <string>
using namespace std;

class BaseClass {
	public:
		void speak(){
			cout << "BaseClass speak function." << endl ;
		}
};

class DerivedClass : public BaseClass {
	public:
		void speak(){
			cout << "DerivedClass speak function." << endl ;
		}
};

int main() {

	DerivedClass myObject ;  //declare DerivedClass object
	BaseClass *myPtr = &myObject;  //create BaseClass type pointer and assign to address of DerivedClass object
	myPtr->speak();  //use the pointer to invoke the method

	BaseClass *otherPtr = new DerivedClass;  //create BaseClass type pointer and assign to new DerivedClass
	otherPtr->speak();  //use the pointer to invoke the method

	return 0;
}

Compile & Run:

BaseClass speak function.
BaseClass speak function.

 

 

Notice, the BaseClass method has been invoked! Whereas, ideally, we would like the DerivedClass method invoked.

 

This is a major problem and is due to the compiler only knowing that a BaseClass type object has been used when invoking the method, instead of doing what we would prefer it do, to invoke the DerivedClass method.

 

The solution to this is Polymorphism, or more specifically virtual functions.

Leave a Reply