Operator Overloading in C++ Programming
Operator Overloading in C++ Programming
The meaning of an operator is always same for variable of basic types like: int, float, double etc.
For example: To add two integers, + operator is used.
However, for user-defined types (like: objects), you can redefine the way operator works. For
example:
If there are two objects of a class that contains string as its data members. You can redefine the
meaning of + operator and use it to concatenate those strings.
This feature in C++ programming that allows programmer to redefine the meaning of an operator
(when they operate on class objects) is known as operator overloading.
1. Unary ++ overloading
#include <iostream>
using namespace std;
class Test
{
private:
int count;
public:
Test(): count(5){}
int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}
2. Operator Overloading of Decrement -- Operator
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(3) { }
Check operator -- ()
{
Check temp;
temp.i = --i;
return temp;
}
void Display()
{ cout << "i = "<< i <<endl; }
};
int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
// Operator overloading
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number: "<< real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main()
{
Complex c1, c2, result;
return 0;
}