In virtual function lesson, why must use pointers instead of object.member()? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

In virtual function lesson, why must use pointers instead of object.member()?

So why we can't use n.attack() and m.attack() to print out the attack? I'm referring to "virtual functions" lesson.

3rd Dec 2016, 9:17 AM
linkiron
linkiron - avatar
4 Answers
+ 2
It's hard to answer without seeing the code, but in general obj.method() and (&obj)->method() work the same way. Perhaps, the lesson tried to emphasize calling virtual method of derived class through bar pointer.
4th Dec 2016, 7:15 PM
Igor B
Igor B - avatar
+ 1
You're right, your code is shorter and more readable. However, if you had a collection of enemies, you can polymorphically attack using pointers to base.
5th Dec 2016, 9:06 AM
Igor B
Igor B - avatar
0
@Igor Berger int main(){ Ninja n; Monster m; Enemy* e1=&n; Enemy* e2=&m; e1->attack(); e2->attack(); return 0;} "We would have the same result by calling the member functions directly from the objects. However, it's more easier and faster to use pointers." Why? I think that's easier and faster to write: int main(){ Ninja n; Monster m; n.attack(); m.attack(); return 0;}
4th Dec 2016, 8:16 PM
linkiron
linkiron - avatar
0
Understood. Thanks a lot!
5th Dec 2016, 9:11 AM
linkiron
linkiron - avatar