Polymorphism Example in C++

If you’ve read my 5 minute guide What Is Polymorphism? and want to see it in action, here’s some C++ code that illustrates the example I mentioned in that post.

I’ve kept the code to header files only for brevity, but as you well know, in the real world, objects would be split out into .h and .cpp files. The program consists of the main.cpp file, a base class called Mammal, and three derived classes called Dog, Cat and Mouse.

1. main.cpp

This is where it all comes together and you see polymorphism in action. I’ve declared an array of pointers to the Mammal base class, and for each one have called the SendLoudNoise() method. The output of the program should look like this:

Woof woof!
--- Twitch my tail ---
--- Sniff the air ---

Which means that although I am calling the method on the base class, it is the derived class that is responding, as it overrides the SendLoudNoise() method in each case.

#include <iostream>
#include "Mammal.h"
#include "Dog.h"
#include "Cat.h"
#include "Mouse.h"

const int cNumAnimals = 3;

int main()
{
	Mammal* pAnimal[cNumAnimals] = { new Dog, new Cat, new Mouse };

	for (int i = 0 ; i < cNumAnimals ; ++i)
	{
		std::cout << pAnimal[i]->SendLoudNoise() << std::endl;
		delete pAnimal[i];
	}

	return 0;
}

2. Mammal.h

The Mammal class, our base class, defines the virtual method SendLoudNoise(), but we never see the text that this method outputs. This proves that our polymorphism example is working correctly.

Note that methods you want to override must be declared as virtual. If you remove this one keyword, the output of the program would be 3 lines of “I am a generic mammal”!

#ifndef MAMMAL_H_
#define MAMMAL_H_

#include <string>

class Mammal {
public:
	Mammal() {};
	virtual ~Mammal() {};

	virtual std::string SendLoudNoise()
	{
		std::string str("I am a generic mammal");
		return str;
	}
};

#endif /* MAMMAL_H_ */

3. Dog.h

The next three files are very similar. Each one inherits from the Mammal class and then overrides the SendLoudNoise() method. Aside from that, they are almost identical.

You don’t have to override a method in a derived class. If you wanted default behaviour, you could specify that in your base class and not mention it in your derived class. Then when that method is called, the object would default to using the base class version.

#ifndef DOG_H_
#define DOG_H_

#include "Mammal.h"

class Dog : public Mammal {
public:
	Dog() {};
	virtual ~Dog() {};

	std::string SendLoudNoise()
	{
		std::string str("Woof woof!");
		return str;
	}
};

4. Cat.h

#ifndef CAT_H_
#define CAT_H_

#include "Mammal.h"

class Cat : public Mammal {
public:
	Cat() {};
	virtual ~Cat() {};

	std::string SendLoudNoise()
	{
		std::string str("--- Twitch my tail ---");
		return str;
	}
};

#endif /* CAT_H_ */

5. Mouse.h

#ifndef MOUSE_H_
#define MOUSE_H_

#include "Mammal.h"

class Mouse : public Mammal {
public:
	Mouse() {};
	virtual ~Mouse() {};

	std::string SendLoudNoise()
	{
		std::string str("--- Sniff the air ---");
		return str;
	}
};

#endif /* MOUSE_H_ */

And that’s all there is to it – a very basic example of using polymorphism to enable interaction with different objects via a base class pointer.

What is Polymorphism?

I was once asked in an interview, “Can you tell me what polymorphism is?”

A straightforward enough question. Or is it? This can be exactly the kind of question that catches you off guard. You’ve used objects for years and of course you know what polymorphism is. But can you explain it in a concise and intelligent manner? This 5 minute guide to polymorphism will lay it all out clearly, so next time someone asks you, you can say, “Yes, let me explain it to you.”

The word

The word is greek in origin and translates literally to ‘many’ + ‘forms’.

In programming

Polymorphism is a descriptive term used in sciences such as biology and chemistry, but it has also been adopted by the object oriented programming methodology.

In a single sentence, polymorphism describes the ability of different objects to be accessed by a common interface.

What does that mean though?

At its most basic, an object is polymorphic if it is related to one or more other objects that can ALL be utilized using the same methods.

To illustrate this with a trivial (and very non-scientific) example, consider the following.

In a room stands a mouse, a cat and a dog. From the far corner of the room, a speaker emits the sudden sound of a balloon popping. The mouse, the cat and the dog all immediately turn toward the direction of the sound. The dog barks, the cat twitches its tail and the mouse sniffs the air.

Programmatically, we can summarize this bizarre scenario as follows:

The mouse, cat and dog are 3 unique objects. They are not the same, but they have some characteristics that are the same. Together, they descend from a more generic superclass, which we will call a mammal. Mammals have ears, which allow them to process sound. The sound of the balloon popping causes each ‘object’ to process the sound in its own way: barking, tail-twitching and sniffing.

These ‘objects’ are polymorphic. Why?

Because although they all behave in different ways, the same method can be used to interact with them, and that method derives from a superclass. And thus here is the crux of the whole thing:

You don’t need to know which type of object you are talking to in order to utilize the method to talk to it.

Polymorphism allows you to talk to an object, without knowing exactly what the object is. If an object is polymorphic, it could be one of many different forms defined by you, the programmer, and descended from a generic base class. All you need to know is what generic type you are talking to and the available methods to talk to it.

Once you’ve called upon the method, the polymorphic type of the object will determine exactly how it behaves in response.

So there you have it. Polymorphism in a nutshell 🙂

I’ve written up the example above in C++ code, so if you want to see it in action, with the actual nuts and bolts of declaring and using objects polymorphically, you can find that here.

What is Object Oriented Programming?

OK, over the next few weeks we’re going to step back a bit from code and command, and instead take a straightforward look at object oriented programming, or OOP*.

Why?

Because it’s often something that crops up in interviews, and the main concepts are things that all programmers should be able to rattle off and feel comfortable talking about. If you come from a low-level, or even machine-level programming background, it’s still A Good Thing to know what this object oriented lark is all about.

OOP deals with objects

Unfortunately there is no standard definition of “object oriented programming” that everyone agrees on, aside from the fact that it uses objects, which is possibly one of the reasons why so many people use it day in and day out, but have trouble defining or explaining what they are actually doing.

OOP requires a particular way of thinking. Instead of planning out a sequence of instructions in your program, you need to think about what you might want it to do, break it up into useful objects, and then allow those objects to interact with each other. There is no set order or route through the code (although all paths should be testable, but that’s a different subject entirely!).

An analogy I often use is to imagine a room full of people talking to each other. Each person is an object, and each object reacts to what other objects around them are saying.

How is OOP implemented?

An object is a concept that is supported by an OOP language, such as Java or C++. Each language varies slightly in it’s approach, but the basic idea is that the language provides you with a way to define an object that you want to use, and then you can generate as many, or few, of those objects as you need.

In C++, you create (or instantiate) objects by declaring a class. A class acts as a template for your object creation. A class contains methods that dictate how the object can be used and how it will respond to stimuli.

The main principles of OOP

This is a subject open to debate, but I think there are 3 core principles of OOP, which memorably spell out the word PIE:

1. Polymorphism

The hardest one to define. Polymorphism describes the ability of different objects to be accessed by a common interface. If that makes no sense, don’t worry, I’ll be covering this next week, and later providing a simple example, so when someone asks you in an interview, “Can you explain polymorphism to me?” you will never be at a loss for words again.

2. Inheritance

Inheritance describes the ability of objects to derive behaviour patterns from other objects. This is an amazing concept which opens up the ground for easily creating interfaces/APIs, and reducing the duplication of code in your program. I’ll take a closer look at this shortly.

3. Encapsulation

Encapsulation describes the ability of objects to maintain their internal workings independently from the program they are used in. This basically means that you define object-related behaviour inside your object, and it therefore becomes self-reliant – you don’t need to have supporting code in place for your object to work correctly. Again, I will cover this in more detail very soon.

So there you have it. The three cornerstones of OOP, and a nice handy definition of each. Next stop: a more detailed look at polymorphism, coming next week!

*Random book recommendation
Whenever I hear the abbreviation OOP, I always think of Douglas Coupland’s novel, Microserfs. It’s getting on a bit now, but is still a fab book about disillusioned Microsoft employees leaving to create a startup. Give it a go: non-affiliated, just-for-the-love-of-it link to it on Amazon here.

Creating Your First C++ Program in Eclipse

Have you seen my C++ Eclipse Masterclass
It’s a series of professional video and text tutorials on using C++ and Eclipse CDT.

This is a tutorial on creating and understanding a ‘Hello World’ program in C++ using Eclipse.

Why? Because in the majority of my other C++ tutorials I will be using Eclipse as the IDE (integrated development environment), and building on a basic project such as this.

I program on Fedora Linux, not Windows, so although your screenshots may differ slightly to mine, Eclipse runs quite happily on both.

Setup

There’s a wealth of information on the Eclipse website that tells you how to install Eclipse for your operating system, but the heads up if you’re a Fedora user is just switch to root (or use sudo) and run:

yum install eclipse-cdt

Create your project

Open eclipse (you’ll find it in the Applications > Programming menu), and if this is the first time you have used it, accept the default workspace and close the welcome window.

Then go to:

Window > Open Perspective > Other > C/C++

This opens the C++ ‘perspective’ in Eclipse, which is a fancy way of saying it makes available the windows and options you need to develop C++ programs.

Now create your first program with:

File > New > C++ Project

Name it Hello, and select the project type as Hello World C++ Project (Figure 1).

create project window
Figure 1: Create a Hello World C++ Project

Click next and accept all the defaults in the Basic Settings window. Click next and again accept all the defaults in the Select Configurations window. Click Finish.

Eclipse will create your project and project file and return you to the main C++ view. You should now be able to see your ‘Hello’ project on the left hand side of the screen, and the contents of the Hello.cpp file in the main window. If you expand the project folder on the left, and then expand the ‘src’ folder underneath it, you will see the location of your program file, Hello.cpp (Figure 2).

hello world project
Figure 2: Your Hello World Project

Your project in action

Now all you have to do is hit ‘Run’ (it’s that little green button that looks like a play symbol).

Note: Eclipse may be set to NOT build automatically, in which case you will get an error about the binary not being found. If this happens, select Build (the hammer icon) before trying to Run.

You should see “!!!Hello World!!!” in the console area at the bottom of the screen (Figure 3). Note that if you prefer a pop-up console window, you can right click and select the ‘Detached’ option on the console tab. Even if you close the window, it will reappear next time you run the program.

console output
Figure 3: Console output

That’s great, but what does it all mean?

Let’s just run through the contents of the Hello.cpp file, so you have an idea of what you have created.

The first 7 lines are just comments. They were created for you by Eclipse and you can edit these to your heart’s content. What’s included at the top of a cpp file varies widely between companies and also depends on personal preference, but bear in mind that the point of the comments is to tell the next person that comes along a little bit about what this file contains.

The first two lines of actual code are:

#include <iostream>
using namespace std;

Any line that starts with a # character is called a ‘preprocessor directive’. The preprocessor makes any requested modifications to your source code before passing it to the compiler. In this example, line 9 is telling the preprocessor to include something called ‘iostream’, which refers to a header file that allows our program to utilize the input/output methods in the iostream library.

I will talk a little more about the preprocessor in a future tuturial, but for now you can look at this line as a succinct way to include pre-existing code.

Line 10 makes use of the using directive to tell the compiler that we are using functions from the standard namespace.

Eh?

OK, a namespace is basically a collection of classes and functions grouped together under an umbrella and given a name. In this case the name is std, and it covers all the things you might want to use from the C++ standard library. Namespaces help resolve the potential issue of classes and functions having the same name and thus causing redefinition errors when you try to compile your program.

In our example, the functions we are using from the standard library are cout and endl. If you didn’t have line 10 in your source file, you wouldn’t be able to use these, because they would not be in scope, or in other words, the compiler would not know what on earth you were referring to*.

Next we have:

int main() {
    cout << "!!!Hello World!!!" << endl;
    return 0;
}

This is the most important part of the file – it’s referred to as the main function and is where our program starts and ends. main is defined only once for any C++ (or C) program, and the name is always all lower-case.

It contains two statements inside a set of curly brackets. The first uses the function cout to print the ‘Hello World’ text to the screen (or standard output), and finishes with endl, to declare an end of line character (the equivalent of pressing the return key after typing in a sentence).

The second statement returns a zero when the program exits. Traditionally a zero return means that the program has executed without errors. It is required here because the main function return type is declared as int (short for integer), meaning a whole number of some value must be returned when the program exits.

Tell me what I’ve learnt

Well, that just about covers it. Of course, you can dig into the details of just these few lines of code and read a huge amount on the hows and whys of it all, but to summarize what this basic tutorial covers, you should have done the following:

1) Created a Hello World C++ program in Eclipse.
2) Run that program and seen the output in the console window.
3) Identified the different parts of the program: comments, preprocessor directive and code.
4) Understood the importance of the main function being our program’s entry and exit point.
5) Noted the use of the std namespace to allow us access to the functions cout and endl.
6) Appreciated the use of these functions to output a text message to the screen.

Phew! That’s enough for today. Look out for the next C++ tutorial, coming soon.

*An alternative to the using directive at line 10 is to qualify each std method with its namespace when it appears in the code, i.e.:

std::cout << "!!!Hello World!!!" << std::endl;

This is considered a better way of doing things, but typing std:: over and over can be a little laborious, hence the widespread use of the using directive on line 10. If you are after more detail, there is a good explanation of this at the C++ FAQ here.