Operator overloading


Using Operator overloading we can overload operators to work with the classes defined by us. For example: consider I have a class to store complex numbers. I may now overload the + – = operators to work with objects of my complex class the way these operators work with int or float data types. This enables me to add objects of complex data type using the + operator. Well its a lot like functions. The only difference I could figure out was that if you use operators instead of functions, you feel like the code is more abstracted. Moreover I think it’s really cool. But I’m sure that there must have been a more beautiful goal behind operator overloading.

Note that just like a function an operator also has to be called by an object.

I studied operator overloading using the following program.


// to study operator overloading by implementing a class on coordinates of a point in space
#include <iostream>
using namespace std;

class coords {
int x,y,z;
public:
coords() {
x=y=z=0;
}
coords( int a , int b , int c ) {
x=a;
y=b;
z=c;
}
void print() {
cout << "(" << x << "," << y << "," << z << ")" ;
}
coords operator+ (coords op2) {
coords temp;
temp.x = x + op2.x;
temp.y = y + op2.y;
temp.z = z + op2.z;
return temp;
}
coords operator-() {
x=-x;
y=-y;
z=-z;
return *this;
}
};

int main() {
coords p1(10,20,30);
cout << "p1.print()\t\t" ;
p1.print();
cout << endl;
coords p2(1,2,3);
cout << "p2.print()\t\t" ;
p2.print();
cout << endl;
coords p3;
cout << "p3.print()\t\t" ;
p3.print();
cout << endl;
p3 = p1 + p2;
cout << "p3 = p1 + p2" << endl;
cout << "p3.print()\t\t" ;
p3.print();
cout << endl;
p3 = - p3;
cout << "p3 = - p3" << endl;
cout << "p3.print()\t\t" ;
p3.print();
cout << endl;
p3 = p1 + p2 + p3;
cout << "p3 = p1 + p2 + p3" << endl;;
cout << "p3.print()\t\t" ;
p3.print();
cout << endl;
return 0;
}

Output:


p1.print()        (10,20,30)
p2.print()        (1,2,3)
p3.print()        (0,0,0)
p3 = p1 + p2
p3.print()        (11,22,33)
p3 = - p3
p3.print()        (-11,-22,-33)
p3 = p1 + p2 + p3
p3.print()        (0,0,0)

3 thoughts on “Operator overloading

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.