Expert C Programming

(Jeff_L) #1

The Key Idea: Polymorphism


Polymorphism refers to the ability to have one name for a function or an operator, and use it
for several different derived class types. Each object will carry out a different variant of the
operation in a manner appropriate to itself. It starts with "overloading" a name—reusing the
same name to represent the same concept with different objects. It is useful because it
means that you can give similar things similar names. The polymorphism comes in when
the runtime system selects which of these identically named functions is the right one.


Let's start by considering our familiar base class of Fruit and adding a method to peel a fruit object.
Once again, we won't fill in the details of peeling, just have it print a message.


#include <stdio.h>


class Fruit { public: void peel(){printf("peeling a base class


fruit\n");}


slice();


juice();


private: int weight, calories_per_oz;


} ;


When we declare a fruit object, and invoke the peel() method like this,


Fruit banana;


banana.peel();


we will get the message


peeling a base class fruit


So far, so good. Now consider deriving our apple class, and giving this its own method for peeling!
After all, apples are peeled somewhat differently than bananas: you can peel a banana with your
thumbs, but you need a knife to peel an apple. We know we can have methods with the same name, as
C++ can cope with overloading.


class Apple : public Fruit {


public:


void peel() {printf("peeling an apple\n");}


void make_candy_apple(float weight);


};


Let's declare a pointer to a fruit, then make it point to an apple object (which inherits from the fruit
class), and see what happens when we try peeling.


Fruit * p;


p = new Apple;


p->peel();

Free download pdf