January 13, 2021

C++ OOP – Polymorphism

As a word, Polymorphism means ‘many forms’. In OOP, it arise when there are classes that are related to each other via inheritance.

So polymorphism in C++ means that a function with the same name exists in different related classes. Therefore, when a call is made, the particular function that would be executed would depend on the object that invokes it.

Let’s take for example, a class Fruit. Then three classes derive from fruit: Banana, Apple and Grape. Then each have a function: describe().

This is shown below

#include <iostream>
using namespace std;

// Base class Fruit
class Fruit {
public:
	void describe(){
		cout<<"Delicious and good for the health";
	}
};


// Derived class, Banana
class Banana: public Fruit {
	void describe(){
		cout<<"Banana: Slender. Yellow when ripe";
	}
};


// Derived class, Orange
class Orange: public Fruit {
	void describe(){
		cout<<"Orange: Round and juicy";
	}
};


// Derived class, Grape
class Grape: public Fruit {
	void describe(){
		cout<<"Grape: Used to make wine";
	}
};

In the example above, the describe() member function is called a polymorphous function.

Now we have created all the classes. We can then create objects from them and override the describe() in the base case. See Function Overriding

//Calling Polymorphous functions
int main() {

	//Create different objects
	Fruit myFruit;
	Banana myBanana;
	Orange myOrange;
	Grape myGrape;

	myFruit.describe();
	myBanana.describe();
	myOrange.describe();
	myGrape.describe();

   return 0;
}

The output of the program is given below:

Delicious and good for the health 
Banana: Slender. Yellow when ripe 
Orange: Round and juicy 
Grape: Used to make wine 

So we can see that the polymorphous functions are called depending on the object that makes the call.

Leave a Reply

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