Upcasting:
First we will look into the upcasting. Converting the derived class pointer to the base class pointer or converting the derived class reference to the base class reference is called as upcasting. It allows public inheritance without the need for an explicit type cast.
A Derived object is-a relationship with the base class. The derived class can get the properties of base class, nothing but it can inherit the data members and member function of the base class.
Means, anything that we can do to a Base object, we can do to a Derived class object.
Downcasting:
Downcasting is exactly opposite to the upcasting the opposite of upcasting. is a process converting a base-class pointer or reference to a derived-class pointer or reference.
It should possible with the explicit type conversion. Because a derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.
for example
#include <iostream>
using namespace std;
class MyPrince {
private:
int id;
public:
void DispId () {
cout << "I am in the principle class" << endl;
}
};
class MyStuent : public MyPrince {
public:
void Disaply () {
cout << "I am in the MyStudent class" << endl;
}
};
int _tmain (int argc, _TCHAR* argv[])
{
MyPrince ocPrince;
MyStuent ocStuent;
// upcast - implicit upcast allowed
MyPrince *prince = &ocStuent;
// downcast - explicit type cast required
MyStuent *pcStudent = (MyStuent *)&ocPrince;
// Upcasting: safe -
prince->DispId ();
pcStudent->DispId ();
// Downcasting: unsafe -
pcStudent->Disaply();
getchar ();
return 0;
}
Credit: http://www.cpphub.com/2014/11/upcasting-and-downcasting-in-c-with.html