In C++, the term "Polymorphism" is the combination of two words "poly" + "morphs" words, which means many forms. It is a Greek word. This property creates the same entity, such as functions and operators that perform differently in several scenarios. Using the polymorphism, we can perform a single task in many ways. It makes the polymorphism an important part of the OOPs Concept.
Simple Example of Polymorphism
Let us take a simple example of polymorphism in C++ using the + operator.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //Main Function
{
int a = 15; //initialize integer values
int b = 20;
string x = "poly"; //initialize string values
string y = "morphism";
cout << "The Value of a + b is: " << a + b <<endl;
cout << "The Value of x + y is: " << x + y;
return 0;
}
Output:
The Value of a + b is: 35
The Value of x + y is: polymorphism
Explanation
In this example, we have taken two (+) operators. The first + operator is used to add two integer values, and the second + operator is used to concatenate two string operands.
Types of Polymorphism:
Polymorphism can be categorized into two categories in C++:
- Compile-Time Polymorphism
- Run-Time Polymorphism
Compile-Time Polymorphism
In C++, the compile-time polymorphism is also known as early binding and static polymorphism. In this polymorphism, the compiler specifies how the operator or function will work depending on the context. It enables multiple functions with the same name but with different parameter lists.
It is implemented using the function overloading and operator overloading.
a) Function Overloading
In C++, function overloading is an important part of object-oriented programming. In function overloading, we can use multiple functions that have the same name but different parameters. Function overloading can be implemented by changing the number of arguments or changing the arguments.
To Read More: Function Overloading
Example of Compile-Time Polymorphism using Function Overloading
Let us take an example to implement the compile-time polymorphism using the function overloading.
Example
#include <iostream>
using namespace std; //using standard namespace
class CppTutorial {
public:
// Function to multiply two integer point values
void multiplication(int x, int y) {
cout << "Integer Multiplication Result = " << x * y
<< endl;
}
// Function to multiply two floating point values
void multiplication(double x, double y) {
cout << "Double Float Result = " << x * y
<< endl ;
}
};
int main() //main function
{
CppTutorial obj;
obj.multiplication(12, 5); // calls show(int)
obj.multiplication(4.5, 2.5); // calls show(double)
return 0;
}
Output:
Integer Multiplication Result = 60
Double Float Result = 11.25
Explanation
In this example, we have taken the class CppTutorial, which contains two multiplication functions with the same name but different parameters. The first multiplication function takes integers, and the second takes double values. In the main function, calling obj.multiplication(12, 5) calls the integer version, while obj.multiplication(4.5, 2.5) calls the floating-point version.
b) Operator Overloading
In C++, operator overloading is a function that provides the operators with a particular meaning for user-defined data types. It is achieved using several operators, such as +, -, *, ==, <<, >>, etc. If we want to use the operator overloading in C++, at least one operand should be a user-defined data type.
To Read More: Operator Overloading
C++ Compile-Time Polymorphism Example using Operator Overloading
Let us take an example to implement the compile-time polymorphism using the operator overloading.
Example
#include <iostream>
using namespace std; //using standard namespace
class CppTutorial_oper {
private:
int value;
public:
// Constructor to initialize value
CppTutorial_oper(int a) : value(a) {}
// Overload * operator
CppTutorial_oper operator * (const CppTutorial_oper& obj) {
return CppTutorial_oper(value * obj.value);
}
// Function to show value
void show() {
cout << "The Multiplication Result of Two Numbers is: " << value << endl;
}
};
int main() //Main function
{
CppTutorial_oper x(12);
CppTutorial_oper y(5);
CppTutorial_oper result = x * y; // Calls overloaded * operator
result.show();
return 0;
}
Output:
The Multiplication Result of Two Numbers is: 60
Explanation
In this example, the operator is overloaded in the CppTutorialoper class to perform multiplication between two objects. Each object stores an integer value. The overloaded operator takes another CppTutorialoper object as an argument, multiplies the internal values of the two objects, and returns a new object containing the result. After that, the show function is used to display the result of the multiplication.
Run-Time Polymorphism
In C++, run-time polymorphism is achieved when the object's method is invoked at the run time instead of compile time. It is also known as late binding or dynamic binding. It enables method overriding in the derived class.
It is implemented using function overriding and virtual functions.
a) Function Overriding
In C++, function overriding is a feature of Oops that enables a derived class to redefine a function that is already provided by its base class. It is used to implement the runtime polymorphism.
In order to allow overriding, the function in the base class should be defined as virtual. In the derived class, the function should have the same name, return type, and parameters.
To Read More: Function Overriding
C++ Run-Time Polymorphism Example using Function Overriding
Let us take an example to implement the run-time polymorphism using the function overriding.
Example
#include <iostream>
using namespace std; //using standard namespace
class Shape // base class
{
public:
virtual void draw() // virtual function
{
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // derived class inheriting shape class
{
public:
void draw() override
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape //derived class
{
public:
void draw() override
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) //main function
{
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rect; //Derived class object
Circle circ;
s=&sh;
s->draw();
s=▭
s->draw();
s= ˆ
s->draw();
}
Output:
drawing...
drawing rectangle...
drawing circle...
Explanation
In this example, we have taken a base class Shape with a virtual function draw. After that, the derived classes Rectangle and Circle are used to override the draw function. In the main function, a base class pointer s is utilized to represent different objects at different times.
b) Virtual Function
In C++, a virtual function is a member function that is declared in the base class. Using the virtual keyword, we can declare the virtual function in the base class. If we declare a method in the base class as virtual and utilize a base class pointer to invoke that method, it invokes the method of the derived class. In the base class, the virtual function helps the derived class method to override that function.
To Read More: Virtual Function
C++ Run-Time Polymorphism Example using Virtual Function
Let us take an example to implement the run-time polymorphism using the Virtual Function.
Example
#include <iostream>
using namespace std; //using standard namespace
class Animal {
public:
virtual void Ani_color() {
cout << "Animal Color Black" << endl;
}
};
class Dog : public Animal {
public:
void Ani_color() {
cout << "Animal Color Gray" << endl;
}
};
int main() //main function
{
Dog dog1;
//pointer of Base type
Animal* ani1 = &dog1;
//calls member function of Derived class
ani1->Ani_color();
return 0;
}
Output:
Animal Color Gray
Explanation
In this example, we have taken a base class Animal that contains a virtual function Anicolor, which is overridden in the derived class Dog. In the main function, a pointer of type Animal* is used to point to an object of the Dog class. When the function Anicolor is called using this base class pointer, it invokes the overridden version in the Dog class because of the virtual keyword.
Differences between Compile-Time and Run-Time polymorphism
Several differences between Compile-Time and Run-Time Polymorphism in C++ are as follows:
| Compile time polymorphism | Run time polymorphism |
|---|---|
| The function to be called is known as the compile time. | The function to be called is known as the run time. |
| It is also known as overloading, early binding and static binding. | It is also known as overriding, Dynamic binding and late binding. |
| Overloading is a compile-time polymorphism where multiple methods have the same name but with a different number of parameters. | Overriding is a run time polymorphism where multiple methods have the same name and number of parameters. |
| It is implemented by function overloading and operator overloading. | It is implemented by virtual functions and pointers. |
| It offers fast execution at the compile time. | It offers slow execution at the run time. |
| It is less flexible because all functions execute at the compile time. | It is more flexible because all function execute at the run time. |
C++ Polymorphism MCQs
1) Which type of polymorphism is implemented by function overriding?
- Run-time polymorphism
- Compile-time polymorphism
- Dynamic polymorphism
- Static polymorphism
2) Which of the following keywords is used to implement the run-time polymorphism in C++?
- virtual
- polymorphic
- final
- override
3) What will be the output of the given program?
#include <iostream>
using namespace std; //using standard namespace
class Employee
{
public : int emp_id;
void show()
{
cout<<"It is the base class" <<endl;
}
};
class department : public Employee{
public :
void show()
{
cout<<"It is the derived class";
}
};
int main() //main function
{
Employee emp1;
department dept;
emp1.show();
dept.show();
};
- It is the derived classIt is the base class
- It is the derived class It is the base class
- It is the base class It is the derived class
- It is the base classIt is the derived class
It is the derived class
4) Which one of the following options shows the polymorphism in C++?
- Overloading &&
- Overloading +=
- Overloading ||
- Overloading <<
5) Which one of the following options is the main advantage of polymorphism in C++?
- Code Optimization
- Type Safety
- Code Reusability
- Memory Efficiency