Pointer | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pointer

why need pointer when i can use n.setAttack(5);//basic polymorphism lesson code? what is actually function of pointer?

19th Jan 2017, 5:57 AM
Sonny Michael
Sonny Michael - avatar
2 Answers
+ 2
This is polymorphism as I understand it. You are operating on a base object, Enemy, that doesn't know about the implementation, only that attack is virtual and will be determined at run time. The benefit is you can write methods accepting the base type rather than individually for each sub.
19th Jan 2017, 9:44 AM
Leon
Leon - avatar
+ 1
int main() { Ninja n; Monster m; Enemy *e1 = &n; Enemy *e2 = &m; e1->setAttackPower(20); e2->setAttackPower(80); n.attack(); m.attack(); } /* Output: Ninja! - 20 Monster! - 80 */
19th Jan 2017, 5:58 AM
Sonny Michael
Sonny Michael - avatar