Re: C++ virtual functions
1. All is ok. When you override(overload) non-virtual function in derived classes it hides the same function in base class.
2. You haven't any virtual function so you haven't virtual table and compiler doesn't know anything about functions from base class.
3. Add word "virtual" to the class Animal then in main() func create derived classes in heap
Code:
int main(int argc, char* argv[])
{
Animal* animal = new Animal();
Animal* wolf = new Wolf();
Animal* fish = new Fish();
Animal* goldfish = new GoldFish();
animal->eat();
wolf->eat();
fish->eat();
goldfish->eat();
return 0;
}
Output should be
I eat like a generic animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
Re: C++ virtual functions
Virtual methods have nothing to do with this situation. If you use your objects through pointers to the base class then the difference between virtual and non-virtual methods will start to show up.
Code:
int main() {
Animal *animal = new Animal;
Wolf *wolf = new Wolf;
Fish *fish = new Fish;
GoldFish *goldfish = new GoldFish;
animal->eat();
wolf->eat();
fish->eat();
goldfish->eat();
cout << "Now through base class:" << endl;
animal->eat();
((Animal*)wolf)->eat();
((Animal*)fish)->eat();
((Animal*)goldfish)->eat();
delete animal;
delete wolf;
delete fish;
delete goldfish;
return 0;
}
Quote:
Originally Posted by result
I eat like a generic animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
Now through base class:
I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.
Re: C++ virtual functions
Thank You. I understood, what you've specified here.
Thank You. I understood what you've specified here.