Deborah R. Fowler
OOP Polymorphism for
C++
Posted on Oct 19 2019Updated Oct 20 2019
This section assumes you have read the basics of OOP for C++, pointers, inheritance and splitting files.
POLYMORPHISM
Polymorphism is the ability to have the program determine which operation you want to use based on what the object type is. In particular the type of data being "pointed" to. We will describe pointers below. This leads to more elegant code.
The classic example is that of a Polygon, Triangle and Rectangle. The Polygon will be the base class, the Triangle and Rectangle child classes. Area will be a function that is define by all three. The pointer to the instance will be used to determine what area function to call. Here let's move forward with Phone, Mobile and Landline.
By using the term virtual in the base class, it indicates that there will be functions with the same name in the derived classes.
Further, if we set any virtual function in the base class to be equal to zero, the base class will be uninstantiable and is referred to as a abstract class.
The function is now called a pure virtual function. Phone is not instantiable but Mobile and Landline are.