+ 1
Because the 'dog' class doesn't have the 'EatFood' method, that method belongs to the 'Animal' class. When you create a dog object and call the method 'EatFood' on it, that dog object is treated as if it is an 'Animal' object, that's why the method works even if it's not defined for the 'dog'. When you define void dog::Eatfood(), you are telling the compiler that the dog class has a method Eatfood and you are defining that. But when it sees the class definition it's not there. That's why throws error. Further answer depends on what you are trying to achieve, if you want a dog's EatFood method to behave differently, you will need to overload it. Just declare EatFood inside the 'dog' class definition. Then you can define Eatfood for both without error. That is also a problem when you start referring a dog as an animal using animal pointer. In that case you need virtual functions, but that's the topic for another discussion.
29th May 2022, 8:59 AM
Vinit Sonawane
Vinit Sonawane - avatar