0

Why does the Mammal speak method get called instead?

int main() {
    Mammal mammal = Cat("CatName", Blue, 9);
    mammal.speak();
}

class Mammal : public Animal{
public:
    virtual void speak() const {
        cout << "Mammal speaks" << endl;
    }
};

class Cat : public Mammal {
public:
    void speak() const {
        cout << "Cat meow!" << endl;
    }
};
Gavin
  • 2,784
  • 6
  • 41
  • 78

2 Answers2

2

Polymorphism only works with pointers or references: You declare mammal to actually be an instance of class Mammal.

Changing that to a pointer or a reference changes the semantics in that the pointer or reference refers to something that is a Mammal.

Mammal const & mammal = Cat();
// or
Mammal * mammal = new Cat();
// don't forget the delete, better:
std::unique_ptr<Mammal> mammal = std::make_unique<Cat>();

In this context you'll probably also quickly come to know object slicing.

Community
  • 1
  • 1
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
1

This is the case, most Java and C# programmers face with c++. You need to dynamically create an object along with a virtual keyword.

So, the correct way to create an object should be

int main
{
  Mammal *mammal = new Cat("CatName", Blue, 9);
  mammal->speak();
}
The Apache
  • 1,076
  • 11
  • 28