I am currently studying polymorphism and its relation to pointers in C++. While I understand how static and dynamic allocation relate to polymorphism, there is one case that has confused me.
class Human
{
public:
virtual void talk();
};
void Human::talk(){ cout << "oink oink" << endl; }
class Doctor : public Human
{
public:
virtual void talk();
};
void Doctor::talk(){ cout << "ouaf ouaf" << endl; }
int main(int argc, char const *argv[])
{
Human h = Doctor();
Human* p = new Doctor();
delete p;
p = &h;
p->talk();
}
What I don't understand is why p->speak()
outputs oink oink
instead of ouaf ouaf
. Is it because p is being reallocated to a location on the stack instead of the heap? If p can be reallocated, why isn't it just pointing to the address of h
and deciding to call the talk()
function in Doctor
at runtime?