OPERATOR OVERLOADING
In C++, 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.
Operator Overloading in C++ is a feature that allows you to redefine the way operators work for user-
defined types (like classes). It enables you to give special meaning to an operator (e.g., +, -, *, etc.)
when it is used with objects of a class
Operators like +, -, *, etc., are already defined for built-in types such as int, float, double, etc. But when
working with user-defined types (like class Complex, class Fraction, or class BigInteger), these
operators don’t work out of the box
Example: Built-in types
int a=10;
float b=20.5,sum;
sum = a + b;
Here, + works because it's predefined for int and float.
Let’s say we have a class A, and we try to add two of its objects using +:
class A
{
// class definition
};
A a1, a2, a3;
a3 = a1 + a2; // Error! '+' not defined for class A
C++ doesn't know how to add two objects of class A. To solve this, we overload the + operator.
To redefine the behavior of an operator so that it works with objects of a user-defined type, while still
retaining its meaning for built-in types.
Syntax of Operator Overloading
return_type operator op (arguments)
{
// function body
}
Program:
#include <iostream.h>
#include <conio.h>
class Complex
{
private:
int real;
int imag;
public:
Complex(int r=0, int i=0)
{
real = r;
imag = i;
}
void input()
{
cout << "Enter real and imaginary parts respectively: ";
cin >> real >> imag;
}
// Operator overloading for +
Complex operator + (Complex c2)
{
Complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
void output()
{
cout << "Output Complex number: ";
cout << real << "+" << imag << "i";
cout << endl;
}
};
int main()
{
Complex c1, c2, result;
clrscr();
cout << "Enter first complex number:\n";
c1.input();
cout << "Enter second complex number:\n";
c2.input();
result = c1 + c2; // calls overloaded operator
result.output();
getch();
return 0;
}
Sample input and output:
Enter first complex number:
34
Enter second complex number:
56
Output Complex number: 8 + 10i
Explanation
Operator Overloading (+)
Complex operator + (Complex c2)
{
Complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
Overloads + so you can add two Complex objects like:
result = c1 + c2;
The function returns a new Complex object containing the sum.