0
#include <iostream>

class Animal
{
public:
    virtual void message() {  std::cout << "Hello from Animal" << std::endl; }
};

class Bird : public Animal
{
public:
    void message() { std::cout << "Hello from Bird" << std::endl; }
};

int main()
{
    Animal a = Bird();
    a.message();

    Animal* b = new Bird();
    b->message();
    delete b;
    
    return 0;
}

Output:

Hello from Animal
Hello from Bird

I know that I have created an Animal object on the stack first, and on the heap later. However, why do they actually call different method implementations? Is there a way to call the base class message() function from the object b?

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
arda30
  • 73
  • 1
  • 1
  • 5
  • 2
    The answers in dupe do not really answer this question, because they fail to mention `virtual` functions. The problem is that object of type `Animal` is always an `Animal` and nothing else, so your `Bird` got sliced and it's not a `Bird` anymore, it's an `Animal`. However, `Animal*` may point to `Animal` or `Bird` or any other derived class. The `Bird` which is pointed to is not sliced, it's still a `Bird`, so the correct function can be called. – Yksisarvinen Nov 16 '21 at 21:22

0 Answers0