Back to the main site

Polymorphism in C++: Polymorphic Arrays

Since I recently did a tutorial explaining polymorphism in Java I think I’ll do one in C++ as well. I’ll be using this as a precursor to design patterns at some point so it’s pretty important we wrap our heads around this! As I’ve mentioned before: polymorphism is the concept of being able to handle objects of different data types using the same interface.


We’re going to use the exact same scenario as I used in my Java tutorial but just so we’re on the same page; we’re going to build and instantiate different classes of objects and make them do something different by calling the same function. This is pretty much the core of polymorphism. First of all we have our Enemy class:


Enemy Class

What we’re doing here is create an abstract class. That is; a class with only pure virtual functions. This is going to serve as our interface for the main program in dealing with our actual objects. Behold!


Ninja and Pirate Classes


Here we have two classes which inherit from the Enemy class and, because Enemy is an abstract class, we need to override the Attack() function in both of them otherwise this simple isn’t going to work. Pure virtual functions need to have any inheriting classes override them. Now for our main function:


Main Function


Ok this is going to warrant a longer explanation of what is actually going on here.

First we create an array of pointers to Enemy and have defined a size of two for this tutorial. Aha, word-play. Next we populate the array by creating new instances of Ninja and Pirate in the two available index locations in enemyArray[]. We’re able to do this because both Ninja and Pirate have inherited from the Enemy class and therefore have an is-a relationship. That is, because the sub class of Ninja has inherited from the baseclass of Enemy, Ninja is-a Enemy. Consequently the Ninja class can do whatever the Enemy class can and more (…had we impleted more functionality in the Ninja class. But the point still stands). The same goes for the Pirate class.


So what we basically have here is an object array also known as a polymorphic array. We then iterate through the array calling the same function and, because Ninja and Pirate have their own implementations of that function, we get the following result:




And there we have it. Congratulations! You have reached the end of the tutorial. Here is a video of an adorable baby gorilla taking a bath.


This entry was posted in Tutorials and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>