In the following code, while constructing obj
in case 1, we construct a derived
class object too, but its member functions are just inaccessible to obj
. So while downcasting (i.e., in case 2), using obj
as source, we have the constructed derived
in it already. Why would obj
need to be polymorphic?
If I confused you with my above description, why doesn't obj
need to be polymorphic when upcasting, but while downcasting it does need to be polymorphic while using dynamic_cast
?
class base
{
public:
base()
{
cout<< " \n base constructor \n";
}
};
class derived : public base
{
public:
derived()
{
cout << " \n derived constructor \n";
}
};
base *obj = dynamic_cast<base*> (new derived); // case 1: explicitly upcasting
derived *OBJ = dynamic_cast<derived*> (obj); // case 2: error