Introduction
In this lab, we will implement the concept of polymorphism in C++. Polymorphism is a concept of Object Oriented Programming where a single function can be used in different ways. There are two types of polymorphism: compile-time polymorphism or static polymorphism and runtime polymorphism or dynamic polymorphism. In this lab, we will focus on runtime or dynamic polymorphism.
Create a new main.cpp file
First, we will create a new C++ file named main.cpp in the ~/project directory:
cd ~/project
touch main.cpp
Add code to implement polymorphism
In this step, we will create a class named Shape. The Shape class will have a virtual function named area(). Then we will create two classes Rectangle and Triangle that will inherit the Shape class and will override the virtual area() function. Once the classes are created, we will create an array of objects of the Shape class and then loop through the array to call the area() function of each object.
#include <iostream>
using namespace std;
class Shape {
public:
virtual float area() {
return 0;
}
};
class Rectangle: public Shape {
public:
float area() {
cout << "Rectangle class area()" << endl;
return 0;
}
};
class Triangle: public Shape {
public:
float area() {
cout << "Triangle class area()" << endl;
return 0;
}
};
int main() {
Shape *shape;
Rectangle rec;
Triangle tri;
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
Compile and run the code
In this step, we will compile and run the code using the following commands:
g++ main.cpp -o main
./main
The output of the above program will be:
Rectangle class area()
Triangle class area()
Summary
In this lab, we learned how to implement the concept of Polymorphism in C++. We created a class with a virtual function named Shape. We then created two classes Rectangle and Triangle that inherited the Shape class and overrode the virtual function area(). Finally, we created objects of the Rectangle and Triangle classes and called the area() function using the object of the base class Shape which resulted in the call to the respective classes.



