Polymorphism

Polymorphism allows us to write code that is less dependent on the types we are trying to manipulate. This can make our code clearer and more efficient. Polymorphism means different forms. If the objects that we code can be more than one type of thing, then we can take advantage of this.

Note

What does polymorphism mean to us? Boiled down to its simplest definition, polymorphism is this: any sub-class can be used as part of the code that uses the super-class. This means we can write code that is simpler and easier to understand and also easier to modify or change. Also, we can write code for the super-class and rely on the fact that no matter how many times it is sub-classed, within certain parameters, the code will still work.

Let's discuss an example.

Suppose we want to use polymorphism to help write a zoo management game where we have to feed and tend to the needs of animals. We will probably want to have a function such as feed. We will also probably want to pass an instance of the Animal to be fed into the feed function.

A zoo, of course, has lots of types of animal—Lion, Elephant, and ThreeToedSloth. With our new knowledge of C++ inheritance, it will make sense to code an Animal class and have all the different types of animal inherit from it.

If we want to write a function (feed) that we can pass Lion, Elephant, and ThreeToedSloth into as a parameter, it might seem like we need to write a feed function for each and every type of Animal. However, we can write polymorphic functions, with polymorphic return types and arguments. Take a look at this definition of the hypothetical feed function:

void feed(Animal& a) 
{ 
   a.decreaseHunger(); 
} 

The preceding function has the Animal reference as a parameter, meaning that any object that is built from a class that extends Animal can be passed into it.

So, you can even write code today and make another sub-class in a week, month, or year, and the very same functions and data structures will still work. Also, we can enforce upon our sub-classes a set of rules for what they can and cannot do, as well as how they do it. So, good design in one stage can influence it at other stages.

But will we ever really want to instantiate an actual Animal?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.163.159