Polymorphism means that a variable of a supertype can refer to a subtype object.
The three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. You have already learned the first two. This section introduces polymorphism.
First, let us define two useful terms: subtype and supertype. A class defines a type. A type defined by a derived class is called a subtype, and a type defined by its base class is called a supertype. Therefore, you can say that Circle is a subtype of GeometricObject and GeometricObject is a supertype for Circle.
The inheritance relationship enables a derived class to inherit features from its base class supertype with additional new features. A derived class is a specialization of its base class; every instance of a derived class is also an instance of its base class, but not vice versa. For example, every circle is a geometric object, but not every geometric object is a circle. Therefore, you can always pass an instance of a derived class to a parameter of its base class type. Consider the code in Listing 15.9.
Listing 15.9 PolymorphismDemo.cpp
1 #include <iostream>
2 #include “GeometricObject.h”
3 #include “DerivedCircle.h”
4 #include “DerivedRectangle.h”
5
6 using namespace std;
7
8 void displayGeometricObject(const GeometricObject& g)
9 {
10 cout << g.toString() << endl;
11 }
12
13 int main()
14 {
15 GeometricObject geometricObject;
16 displayGeometricObject(geometricObject);
17
18 Circle circle(5);
19 displayGeometricObject(circle);
20
21 Rectangle rectangle(4, 6);
22 displayGeometricObject(rectangle);
23
24 return 0;
25 }
The function displayGeometricObject (line 8) takes a parameter of the Geometric-Object type. You can invoke displayGeometricObject by passing any instance of GeometricObject, Circle, and Rectangle (lines 16, 19, 22). An object of a derived class polymorphism can be used wherever its base class object is used. This is commonly known as polymorphism (from a Greek word meaning “many forms”). In simple terms, polymorphism means that a variable of a supertype can refer to a subtype object.
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.