0

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?

Abhi V
  • 714
  • 1
  • 4
  • 19

1 Answers1

2

The first line Human h = Doctor(); First h is created then Doctor object is created and then copy constructor of human is called. H is declared as Human so it will remain human after copy construction.

#include <iostream>

using namespace std;

class Human
{
    public:
        virtual void talk();
        Human()
        {
            cout<<"Human"<<endl;
        }
        Human(const Human & h)
        {
            cout<<"Copy Human"<<endl;
        }
};

void Human::talk(){ cout << "oink oink" << endl; }

class Doctor : public Human
{
    public:
        virtual void talk();
        Doctor()
        {
            cout<<"Doctor"<<endl;
        }
        Doctor(const Human & h)
        {
            cout<<"Copy Doctor"<<endl;
        }
};

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();

}
user1438832
  • 493
  • 3
  • 10