+ 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.
4 Respuestas
+ 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.
+ 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.
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;}
0
Understood. Thanks a lot!