Whats is the benefit if we use enemy pointer to the type of it's inherited class ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Whats is the benefit if we use enemy pointer to the type of it's inherited class ?

If we use a class like Enemy and then Ninja , Monster which inherits the property of Enemy class then in the main function we declare two pointer to the Enemy class having the address of It's derived class object like this .. 👇👇 int main() { Ninja n; Monster m; Enemy *e1 = &n; Enemy *e2 = &m; } We could also separately declare that without pointing to enemy object like Ninja n; then pointer to it's own type Ninja *p = &n ; https://www.sololearn.com/learn/CPlusPlus/1911/ But what's the benefit of the way we used above .... please help me 🙏🙏

19th Dec 2018, 6:25 AM
Atik🇧🇩
Atik🇧🇩 - avatar
2 Answers
+ 4
AFAIK, you may want to override a virtual function defined in the base class (Enemy class) like this class Enemy { public: virtual void kill() { cout << "Enemy gets killed\n"; } }; by an object from the derived class class Ninja : public Enemy { public: void kill() { cout << "Ninja gets killed\n"; } }; in order to avoid, for example, overloading a global function to perform the correct action like so // global function prototype void f(Enemy *x); // notice that the formal parameter is of type `Enemy *` int main() { // objects creation Ninja *n = new Ninja; Enemy *e = new Enemy; // invoking the global function f(e); f(n); } // Function definition void f(Enemy *x) { x->kill(); } Output: Enemy gets killed Ninja gets killed Without being virtual: Enemy gets killed Enemy gets killed
19th Dec 2018, 12:23 PM
Babak
Babak - avatar
+ 2
If you have plenty of Monsters, Ninjas, and several kind of other "objects" in a game on the same spot, and you might attack them with a bomb or something, the explosion would damage all of them. So if you point to them with enemy pointers, you could just loop through an array of enemies and don't mind about the different types instead of calling each object separately and add damage. This makes coding easier and closer to the real applications. So it's a nice feature ;) There are also other examples depending on the context. Tip: read the comments below these lessons. They often provide useful explanations and your question is actually already answered there 😉
19th Dec 2018, 9:38 AM
Matthias
Matthias - avatar