upcasting in c++
Upcasting in C++
Upcasting is the process of treating a derived class object as an object of its base class. It involves assigning a derived class object to a base class pointer or reference. Upcasting is safe and does not require any explicit type casting operator. The base class pointer or reference can access only the members and functions that are inherited from the base class.
Here is an example to illustrate upcasting in C++:
class Base {
public:
void baseFunction() {
cout << "Base function" << endl;
}
};
class Derived : public Base {
public:
void derivedFunction() {
cout << "Derived function" << endl;
}
};
int main() {
Derived derivedObj;
Base* basePtr = &derivedObj; // Upcasting
basePtr->baseFunction(); // Accessing base class function
// basePtr->derivedFunction(); // Error: Cannot access derived class function
return 0;
}
In the above example, the Derived
class is derived from the Base
class. The Derived
class inherits the baseFunction()
from the Base
class and also has its own derivedFunction()
.
In the main()
function, an object of the Derived
class is created. Then, a pointer of type Base*
is assigned the address of the Derived
object, which is an example of upcasting. The basePtr
can only access the members and functions of the Base
class. Attempting to access the derivedFunction()
using the basePtr
will result in a compilation error.
Upcasting is useful in scenarios where you want to treat objects of derived classes as objects of their base class, allowing for polymorphism and code reusability.