If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

C++ Polymorphism: What is polymorphism?

Q: What is polymorphism?

A: I'm glad you asked me that...

Without going into great detail, polymorphism is a mechanism that allows you to implement a function in different ways. For example, you might be modelling birds, and you want them to fly. Some birds flap their wings like crazy, others glide majestically. However, the function that moves a bird from one place to another doesn't care how the bird flies, only that it does fly. This is an important principle to grasp - the what is important, the how is irrelevant. So your "migrate" function could be used with any bird class that is capable of flying, whether it's a sparrow or an albatross. What we're saying, then, is that these birds share the ability to fly, though the way they fly may differ. The "ability to fly" is an abstraction. Note again the distinction between what it does and how it does it. The abstraction says what it does: it says nothing about how it does it. We represent that in C++ with the "pure virtual function":

Code:

class bird
{
public:
virtualvoid fly() = 0;
};

What this (abstract) class is saying is "all birds can fly". (Note that, on this definition, emus and ostriches are not birds because they can't fly. This is a very important point, but unfortunately outside the scope of this FAQ.)

Your migrate function now only needs to know about the "bird" class in order to be written:

Code:

void migrate(bird* tweetiepie)
{
// ...
tweetiepie->fly();
// ...
}

So far, so good. But "bird" only defines the "what" part - it says nothing about the "how". And that's another thing the pure virtual function does: you cannot create an object of type "bird" - you've got to be more specific and create a particular kind of bird. This is where inheritance and polymorphism come in: if we want to do some useful work, we need some real birds:

Because we've derived both of these from the abstract class bird, we can use one wherever a bird is expected. Specifically, we can give migrate() a swallow or an albatross, and it will still work.

Code:

swallow s;
albatross a;
migrate(&s);
migrate(&a);

When the swallow is passed to migrate, the call to fly() in there will result in "flap_wings_like_crazy", but when the albatross is passed in, the same call will result in "glide_majestically_over_the_waves".

And that's polymorphism.

We will meet polymorphism again when I discuss virtual functions and virtual destructors (coming soon, honest).