Downcast in object orientated programming places a cast in the code to give the compiler more specific type information. Show a program example.
Solution
Downcast is the conversion of pointer or reference of base class type to pointer or reference type of its derived class, going down in the inheritance tree. This is achieved with help
of dynamic_cast operator that safely downcast at run time.
#include <iostream>
using namespace std;
class Parent
{
public:
void sleep()
{
cout<<\"Go to sleep\"<<endl;
}
};
class Child: public Parent
{
public:
void gotoSchool()
{
cout<<\"Go to school \"<<endl;
}
};
int main( )
{
Parent parent;
Child child;
// upcast - implicit type cast allowed
Parent *pParent = &child;
// downcast - explicit type case required
Child *pChild = (Child *) &parent;
pParent -> sleep();
pChild -> gotoSchool();
return 0;
}
OUTPUT:
Go to sleep
Go to school
Derived Child class from a Parent class, adding a member function,gotoSchool(). It wouldn\'t make sense to apply the gotoSchool() method to a Parent object. However, if implicit downcasting were allowed, we could accidentally assign the address of aParent object to a pointer-to-Child
.