0

Why are virtual functions needed? if you had a base class with an attack function and you had a derived class (n) with an attack function could you not just use n.attack(); to access that function?

virtual functions

27th Aug 2016, 10:25 PM
Rondes
3 Answers
+ 1
That has nothing to do with virtual function. Consider this instead: you have a base class Enemy with a virtual function attack and two derived classes Ninja and Monster with their own implementation of attack. You create a Ninja object ninja and a Monster object monster, and then you create two Enemy pointers e1 and e2 and assign them the address of ninja and monster respectively. You can use e1->attack() and e2->attack(), and this will call the attack of Ninja and Monster respectively.
27th Aug 2016, 11:18 PM
Zen
Zen - avatar
+ 1
You could call monster.attack() of course, but that's not the point. Imagine that you only have the Enemy pointers. For example, say you have a function taking a list of Enemy pointers as argument, and you want to call their attack. The correct one will be called each time.
27th Aug 2016, 11:33 PM
Zen
Zen - avatar
0
could you not call monster.attack()?
27th Aug 2016, 11:26 PM
Rondes