I am learning C++ inheritance, so I tried this code by creating a Base class dynamically and made a downcast to its Derived class (obviously its not valid to downcast) in order
first of all, this is no valid downcast. The real type of new parent() indeed is parent and not child. Downcasting is only allowed if the real (also called dynamic) type is child but the pointing object is a parent at the moment.
The other way around would make more sense. If you create a child and assign it to a parent pointer, this would be fine. But even then: Unless who is virtual the static type instead of the dynamic type decides which function is called.
Example:
class parent{
public:
void who(){
cout << "I am parent";
}
~virtual parent() {}; // important to have that in class hierarchies where you might use a child that is assigned to a parent pointer!
};
class child : public parent{
public:
void who(){
cout << "I am child";
}
};
int main(){
parent *c = (parent *)new child();
c->who(); // output would still be parent because who() is not virtual
delete c; // important! never forget delete!
return 0;
}
If you use, on the other hand,
virtual void who();
then, the output would be "I am child" like you would expect.