POLYMORPHISM
The word “polymorphism” means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form. A real-life example of
polymorphism is a person who at the same time can have different characteristics. A man at the
same time is a father, a husband, and an
employee. So the same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-Oriented
Programming. Types of Polymorphism
Compile-time Polymorphism
Runtime Polymorphism
Operator Overloading
Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an
existing operator in C++ without changing its original meaning.
It has the ability to provide the operators with a special meaning for a data type, this ability is known
as operator overloading. Operator overloading is a compile-time polymorphism. For example, we
can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using
+. Example:
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is used with between two Complex objects Complex
operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
The word “polymorphism” means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form. A real-life example of
polymorphism is a person who at the same time can have different characteristics. A man at the
same time is a father, a husband, and an
employee. So the same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-Oriented
Programming. Types of Polymorphism
Compile-time Polymorphism
Runtime Polymorphism
Operator Overloading
Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an
existing operator in C++ without changing its original meaning.
It has the ability to provide the operators with a special meaning for a data type, this ability is known
as operator overloading. Operator overloading is a compile-time polymorphism. For example, we
can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using
+. Example:
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is used with between two Complex objects Complex
operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;