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 to make this dynamically created Base object to be pointed by a Derived class pointer. But when I call a method who()
through this Derived pointer it invokes the Derived class method instead of Base class method.
According to my assumption no object is created for the Derived class, then how could it be possible to invoke the non created Derived class object's method instead of actually created Base class object?
I googled for this phenomenon but couldn't find a clear and crispy explanation for invoking a non created Derived class object's method. If it is according to the standard then explain me how it works.
I know the story will be different if I make the method virtual
but the method used here is not virtual
.
class parent{
public:
void who(){
cout << "I am parent";
}
};
class child : public parent{
public:
void who(){
cout << "I am child";
}
};
int main(){
child *c = (child *)new parent();
c->who();
return 0;
}
The output is I am child
but I expected I am parent
Edit:: I didn't freed up the memory in the above code and made an invalid downcast because I just wanted to see what happens. So just explain this behavior of invoking methods only.