C++ compiler can use operators on basic types such as int, float and string. When you create a custom class and try to use an operator, the compiler does not know how to deal with provided information. Here is where operator overloading comes in. C++ allows operator overloading for specific types - effectively you can define custom behaviors for a wide range of operators.
In this example, I use a custom Point class which has x and y values. Shown operators (+,-,*,/,>,<,>>,<<) are altered to exhibit a particular behavior as to compare those values.
//overloading operators
#include "stdafx.h" //-- for Visual Studio only
#include <iostream>
#include <string>
using namespace std;
class Point {
int _x, _y;
public:
Point(int x, int y) :
_x(x), _y(y) {
}
int x() const {
return _x;
}
int y() const {
return _y;
}
bool operator > (const Point &p)const {
return (_x + _y) > (p._y + p._y);
}
bool operator < (const Point &p)const {
return (_x + _y) < (p._x + p._y);
}
bool operator == (const Point &p)const {
return (_x == p._x) && ( _x == p._y);
}
friend ostream& operator << (ostream& os,const Point &p) {
os << "(" << p._x << "," << p._y << ")";
return (os);
}
friend istream& operator >> (istream &input, Point &p)
{
input >> p._x;
input >> p._y;
return input;
}
Point operator = (Point &p) {
_x=p._x;
_y=p._y;
return *this;
}
Point operator + (const Point &p) const {
return Point(_x+p._x, _y+p._y);
}
Point operator - (const Point &p)const {
return Point(_x-p._x, _y-p._y);
}
Point operator * (const Point &p)const {
return Point(_x * p._x, _y * p._y);
}
Point operator / (const Point &p)const {
//---check for denominator - 0
if (p._y == 0)return Point(0, 0);
return Point(_x / p._x, _y / p._y);
}
};
int main()
{
Point alpha(2,2), beta(4,4), gamma(8,8);
cout << "3 points (custom class)" << endl;
cout << endl;
cout << alpha << " alpha" << endl;
cout << beta << " beta" << endl;
cout << gamma << " gamma" << endl;
cout << endl;
cout << "overloaded operators (+,-,*,/,>,<,>>,<<)" << endl;
cout << endl;
cout << (alpha + beta) << " alpha + beta" << endl;
cout << (alpha + beta + gamma) << " alpha + beta + gamma" << endl;
cout << (alpha - beta) << " alpha - beta" << endl;
cout << (alpha * beta) << " alpha * beta" << endl;
cout << (beta / alpha) << " alpha / beta" << endl;
cout << (alpha > beta) << " is alpha bigger than beta (0=false)" << endl;
cout << (alpha < beta) << " is alpha smaller than beta (1=true)" << endl;
cout << endl;
cout << "3 Points (unaltered after using operators)" << endl;
cout << endl;
cout << alpha << " alpha" << endl;
cout << beta << " beta" << endl;
cout << gamma << " gamma" << endl;
cin.get();
return 0;
}