What is Upcasting and Downcasting in C++
In C++ we can create a pointer references between the parent and child classes and form a βis aβ? relation between them. There are two types of casting that can be done β
- Upcasting
- Downcasting
In C++ we can create a pointer references between the parent and child classes and form a βis aβ? relation between them. There are two types of casting that can be done β
In simple terms using upcasting allows us to treat the child class object as if it were the parent class object. There are two ways of creating upcasting relationship β
Creating parent class pointer and assigning it to the base classes reference.
Parent* parentObj; // Parent class pointer
Child childObj; // Creating child class object
parentObj = &childObj; // assigning to address reference of base class object
Creating Parent Classes referenced object and assigning it to the child class object
Parent &parentObj; // Parent class reference
Child childObj; // Creating child class object
parentObj = childObj; // direct assignment
Facts
The object is not changing
However, even with the child class objects we will only be able to access the data and function members of the parent class
#include
using namespace std;
// This is Parent class
class Parent
{
public:
void print()
{
cout << "Parent Class printing" << endl;
}
};
// This is Child class
class Child : public Parent
{
public:
// as we see that it is already declared in the parent function
void print()
{
cout << "Child Class printing" << endl;
}
};
int main()
{
Parent *parent_object;
Child child_object;
parent_object = &child_object;
// catch of the program is here
// also as we are dealing with pointers instead of . we need to use ->
parent_object->print();
return 0;
}
Parent Class printing
Downcasting is vice versa as of Upcasting. In upcasting we created parent class pointer reference to child class address reference. We can not do this implicitly thus, we follow explicit form, which is β
#include
using namespace std;
// This is Parent class
class Parent
{
public:
void print()
{
cout << "Parent Class printing" << endl;
}
};
// This is Child class
class Child : public Parent
{
public:
// as we see that it is already declared in the parent function
void print()
{
cout << "Child Class printing" << endl;
}
};
int main()
{
Parent *parent_object;
Child *child_object = (Child* ) &parent_object;
// catch of the program is here
// also as we are dealing with pointers instead of . we need to use ->
child_object->print();
return 0;
}
Child Class Printing