Reputation: 760
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".
Upvotes: 0
Views: 48
Reputation:
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();
Upvotes: 3
Reputation: 60017
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();
Upvotes: 2