0

I am trying to override the method in parent class Animal speak function but it is not working. Wrote exactly similar code in java it prints correct message but not in C++. Do I have to do something different in C++ to make this work?

class Animal{
public:
    virtual void Speak(){
        cout<<"Animal Speak"<<endl;
    }
};

class Cat:public Animal{
    void Speak() override {
        cout<<"Cat speak"<<endl;
    }
};

class Dog:public Animal{
void Speak() override {
        cout<<"Dog speak"<<endl;
    }
};

int main() {
    Cat cat;
    Dog dog;
    Animal ani[]={cat,dog};
    ani[0].Speak();
    return 0;
}

I am expecting "Cat Speak" to printout in console but it is printing "Animal Speak".

LilRazi
  • 690
  • 12
  • 33
  • This is called [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing) – NathanOliver Nov 24 '17 at 02:03
  • *I am expecting "Cat Speak" to printout in console* -- If you were using Java, maybe so. But this is C++ where the rules are different. – PaulMcKenzie Nov 24 '17 at 02:11

2 Answers2

3

In the line Animal ani[]={cat,dog};, cat and dog are copied by value into 2 Animal objects. Object slicing occurs during the copying. So, ani[0].Speak() actually uses an object of type Animal, not Cat or Dog.

The member function call is also not virtual because the object is used by value. Virtual call is performed only through pointer or reference.

Animal* dog_as_animal = &dog;
dog_as_animal->Speak();
Animal& cat_as_animal = cat;
cat_as_animal.Speak();
2

It is copying a cat object to an animal object. Ditto with dog.

You can verify this by implementing a copy constructor.

I think you need:

Animal* ani[]={&cat,&dog};
ani[0]->Speak();
Ed Heal
  • 59,252
  • 17
  • 87
  • 127