Suppose I have a class, Animal, that contains the virtual method eat(). Now suppose Dog is derived from Animal, and also implements eat().
Now somewhere else, I have a class Barn with a feed method that takes Animal& as a parameter. How can I force class Barn to call Dog's eat, when a Dog is passed to feed?
fluidDelusions
0
Newbie Poster
Recommended Answers
Jump to PostWhen creating the eat() function in Animal , set it equal to 0. for example:
class Animal { void eat()=0; };
Jump to PostNow that I think about it, what you have should already work. When you call the eat method, is it calling the wrong one?
Jump to PostHere's the deal - you need the 'virtual' word in the Animal class when defining eat(). (Don't do the =0)
See this example:
#include <iostream> using namespace std; class Animal { public: virtual void eat() { cout<<"I'm an animal"<<endl; } }; class Dog : public Animal …
Jump to PostNot sure about your question, I can tell you that I only got what you wanted to work (with the vectors, when I made the vector store pointers of Animal). I think it has something to do with the fact that push_back makes a copy of the parameter, so I …
All 14 Replies
winbatch
7
Posting Pro in Training
fluidDelusions
0
Newbie Poster
winbatch
7
Posting Pro in Training
fluidDelusions
0
Newbie Poster
fluidDelusions
0
Newbie Poster
winbatch
7
Posting Pro in Training
fluidDelusions
0
Newbie Poster
fluidDelusions
0
Newbie Poster
winbatch
7
Posting Pro in Training
fluidDelusions
0
Newbie Poster
winbatch
7
Posting Pro in Training
fluidDelusions
0
Newbie Poster
winbatch
7
Posting Pro in Training
NosKills
0
Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.