Overloading an operator is similar to defining a non-static member function of a class, except that now a function name becomes the keyword operator followed by the operator symbol being overloaded. In the example code below, the operators: +, -, *, and / are overloaded to add, subtract, multiply, and divide Fraction objects. One Fraction object is a fraction that has a numerator and a denominator.

#include <iostream>
#include <conio.h>
using namespace std;
class Fraction{

int numerator;
int denominator;
public:
Fraction(){
numerator=0;
denominator=0;
}

Fraction(int num,int den){
numerator=num;
denominator=den;
}

Fraction operator+(Fraction f){
Fraction r;
r.numerator=(numerator*f.denominator)+(denominator*f.numerator);
r.denominator=denominator*f.denominator;
return(r);
}

Fraction operator-(Fraction f){
Fraction r;
r.numerator=(numerator*f.denominator)-(denominator*f.numerator);
r.denominator=denominator*f.denominator;
return(r);
}

Fraction operator*(Fraction f){
Fraction r;
r.numerator=numerator*f.numerator;
r.denominator=denominator*f.denominator;
return(r);
}

Fraction operator/(Fraction f){
Fraction r;
r.numerator=numerator*f.denominator;
r.denominator=denominator*f.numerator;
return(r);
}
void printF(){
cout<<numerator<<"/"<<denominator<<endl;
}

};

int main(){

Fraction f1(1,4);
Fraction f2(2,3);
Fraction resultSubtract=f1-f2;
Fraction resultMultiply=f1*f2;
Fraction resultDivide=f1/f2;
resultSubtract.printF();
resultMultiply.printF();
resultDivide.printF();
getch();
return 0;

}

Besides overloading the binary operators, you might want to overload unary operators, such as ++ and --. When a unary operator is overloaded by using a non-static member function, you do not need to pass an object to the operator function. In the example code below, two operator functions are defined. One function is to overload the prefix version of the operator ++. Another one is to overload the postfix version of the operator ++. For the prefix version, you do not to write a parameter of the function. For the postfix version you need to write a parameter of the function. However, this parameter is not used by the function. It is only used by compiler to distinguish between the prefix and postfix forms of the operator ++.

#include <iostream>
#include <conio.h>
using namespace std;

class Point{

int x;
int y;
public:
Point(){
x=0;
y=0;
}
Point(int x,int y){
this->x=x;
this->y=y;
}
Point operator++(){
x++;
y++;
return *this;
}
Point operator++(int){
Point temp=*this;
x++;
y++;
return temp;
}
void printP(){
cout<<"("<<x<<","<<y<<")"<<endl;
}
};

int main(){
Point p(10,100);
Point p1=p++;
Point p2=++p;
p1.printP();
p.printP();
p2.printP();
p.printP();

getch();
return 0;

}