0
What is the use of virtual in this program
#include<iostream> using namespace std; class Mammal { public: int getLegCount() { return 4; } }; class Monkey : public Mammal { public: int getLegCount() { return 2; } }; class Goat : public Mammal { }; int main() { Monkey m; Goat g; cout << "Monkeys have " << m.getLegCount() << " legs \nGoats have " << g.getLegCount() << " legs.\n"; return 0; } In the code above i am able to override base function "getLegCount" even without using virtual keyword...So what is the use of virtual keyword...
3 Answers
+ 2
virtual is used with polymorphism. It allows the base class to call the correct method.
If getLegCount in the Mammel class was marked virtual this would be the output for the following code:
Mammel* m = new Monkey; // Polymorphism
std::cout << m->getLegCount(); // output 2
It called Monkey's getLegCount.
If it was not marked virtual then it would have called Mammel's getLegCount, resulting in an output of 4.
0
Dennis So does it mean virtual keyword only help pointers to use polymorphism...? or is their something else that they do?
0
Hmm, not sure what you mean. Here, read this instead:
https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm