PDA

View Full Version : C++ virtual functions



sonulohani
23rd May 2012, 06:15
Sir,
I have a query about this vitual function. Look at this example:-

using namespace std;

#include <iostream>
class Animal {
public:
void eat() { //I have removed the virtual keyword here.
cout << "I eat like a generic animal.\n";
}
// polymorphic deletes require a virtual base destructor
//virtual ~Animal() {
//}
};
class Wolf : public Animal {
public:
void eat() {
cout << "I eat like a wolf!\n";
}
};
class Fish : public Animal {
public:
void eat() {
cout << "I eat like a fish!\n";
}
};
class GoldFish : public Fish {
public:
void eat() {
cout << "I eat like a goldfish!\n";
}
};
int main() {
Animal animal;
Wolf wolf;
Fish fish;
GoldFish goldfish;
animal.eat();
wolf.eat();
fish.eat();
goldfish.eat();
return 0;
}

The output is :-
I eat like a generic animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!

Instead of this:-

I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.

Why is this happening? Is there something wrong? If it is possible then what is the use of this virtual function. Please answer me.

Thank You.

AlekseyOk
23rd May 2012, 07:56
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



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!

wysota
23rd May 2012, 08:06
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.


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;
}


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.

sonulohani
23rd May 2012, 09:17
Thank You. I understood, what you've specified here.

Thank You. I understood what you've specified here.