In this lesson, we will learn about Polymorphism in C++ and its use with the help of an example.
The term polymorphism is derived from the Greek words “poly” and “morphos,” where poly denotes a great number and morphos denotes a variety of shapes. Polymorphism, defined as having “many forms,” happens when there are numerous classes related to one another by inheritance.
We can inherit attributes and methods from another class through inheritance, as we mentioned in the previous lesson. Polymorphism uses these techniques to carry out various tasks, which enables us to carry out a single activity in various ways. Function overloading, operator overloading, function overriding, and virtual functions can all be used to implement it.
Let’s look at a case in which function overriding is being used.
#include <iostream> #include <string> using namespace std; // Base class class Shape { public: void drawShape() { cout << "Many Shapes \n"; } }; // Derived class class Circle: public Shape { public: void drawShape() { cout << "Circle \n"; } }; // Derived class class Square: public Shape { public: void drawShape() { cout << "Square\n"; } }; int main() { Shape myShape; Circle myCircle; Square mySquare; myShape.drawShape(); myCircle.drawShape(); mySquare.drawShape(); return 0; }
Output
Many Shapes Circle Square
Consider a base class called Shape, for instance, with a method called drawShape()
. Square and Circle are derived from the Shape class, each with unique shapes.
One of the fundamental ideas of OOP languages, polymorphism, explains the idea of using many classes with the same interface. Each of these classes is capable of offering a unique interface implementation.
This concludes the C++ Polymorphism lesson. In The next lesson, you will learn about Encapsulation in C++ and its usage.