+ 1

Base Class Type Pointers

So I noticed that the example uses base class (enemy) type pointers to point at derived class (ninja/monster) type objects. The program works just as well with derived class type pointers being used as well. My question is this: when pointing to a derived class type object, does it matter what type of pointer you use? The result seems to be the same, but my gut tells me one way is best practice because of how things are handled behind the scenes.

9th May 2018, 12:35 AM
Domingo Gonzales III
2 Respostas
+ 2
You are correct that using base class or derived class pointers makes no difference when you are just using them simply. Enemy *e = new Ninja(); works just as well as Ninja *n = new Ninja();. It is said that using the base class is better because "you don't need to know the type of the object. All you need to know is that it is derived from the base class." What does this look like in practice? Well, if you look at my example code, you can see that I have an array of pointers of the base class (Enemy). I can point to BOTH Ninjas and Monster objects using this array of pointers. If I had chosen to make the array type pointers of one of the derived classes, I could only point to that type of object and not the other. With base class pointers as the array type, I can even traverse the array using a for loop and call the same functions to use on both the Ninjas and Monsters that are pointed to. Notice that the attack() function is called, and the correct implementation of the function based on whether the object is a Ninja or Monster is called. So while you can use either base class pointers or derived class pointers for simple applications, using the base class pointers provides more flexibility when you are trying to group together objects of different types that all are derived from the base class. Additionally, if you use base class pointers, you have the flexibility to use the pointer to point at different types of objects throughout your program. You can have it start by pointing at a Ninja object, but then use it to point to a Monster object later. https://code.sololearn.com/cap1B6k26Bez/?ref=app
14th May 2018, 4:08 AM
Caroline
+ 2
Fantastically thorough answer Caroline! You're example code was a great visual. I'll be sure to stick to using base class pointers.
14th May 2018, 2:30 PM
Domingo Gonzales III