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...

13th Oct 2018, 1:30 PM
Rashim Narayan Tiku
Rashim Narayan Tiku - avatar
3 Antworten
+ 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.
13th Oct 2018, 2:20 PM
Dennis
Dennis - avatar
0
Dennis So does it mean virtual keyword only help pointers to use polymorphism...? or is their something else that they do?
13th Oct 2018, 4:46 PM
Rashim Narayan Tiku
Rashim Narayan Tiku - avatar
0
Hmm, not sure what you mean. Here, read this instead: https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm
13th Oct 2018, 4:57 PM
Dennis
Dennis - avatar