0

It seems like I have a confusion about polymorphism and/or pointers. Please see the simple code and the outputs below.

class Cell {
    public:
        virtual void call() { std::cout<<"I am a cell"<<std::endl; };
};

class Human: public Cell {
    public:
        void call() override  { std::cout<<"I am a human"<<std::endl; };
};

int main()
{
    Cell *c = new Cell();
    Human h;

    c = &h;

    (*c).call(); // ->>>>>> First call

    auto temp = *c;
    temp.call(); //  ->>>>>> Second call

    auto temp2 = c;
    temp2->call(); //  ->>>>>> Third call

    auto func1 = [&](Cell *x) {
        x = &h;
        return *x;
    };

    func1(c).call(); // ->>>>>> Fourth call

    return 0;
}

The outputs are as follows:

I am a human
I am a cell
I am a human
I am a cell

Could someone please explain me what is going on here?

huckfin
  • 17
  • 1
  • 7
  • 1
    What exactly do you not understand? Which of the four calls confuses you? – Thomas Sablik Jan 22 '20 at 14:59
  • 1
    `Cell *c = new Cell(); Human h; c = &h;` -- You've created a memory leak by replacing `c` with another address. – PaulMcKenzie Jan 22 '20 at 15:00
  • `*c` is a `Cell&` that references a `Human`; `temp` is a `Cell` (not a `Human` at all); `temp2` is a `Cell*` pointing to a `Human`; `func1(c)` is a `Cell` (also not a `Human`). – molbdnilo Jan 22 '20 at 15:03
  • I do not understand why the first call and the second call differs. They are basically the same, right? – huckfin Jan 22 '20 at 15:05
  • @huckfin `auto` is never a reference. Write `auto& temp` and `[&](Cell *x) -> Cell&` and look at the difference. – molbdnilo Jan 22 '20 at 15:10
  • You should replace `Cell *c = new Cell(); Human h; c = &h;` with `Human h; Cell *c = &h;` – Thomas Sablik Jan 22 '20 at 15:38
  • You can use https://godbolt.org/z/ixZ9Kq for such questions. You will find that `(*c).call();` uses the vtable (line 13: `call qword ptr [rcx]`) and `temp.call();` doesn't use the vtable (line 18 `call Cell::call()`). – Thomas Sablik Jan 22 '20 at 15:40
  • 1
    @ThomasSablik thanks so much for the clarification. I wasn't aware of godbolt, it must help in a lot of situations like this. – huckfin Jan 22 '20 at 16:01

0 Answers0