Operator Overloading
Operator Overloading
return-type class-name::operator#(arg-list){
// operation to be performed
Most C++ operators can be overloaded. Only the following operators cannot
be overloaded- (1) Preprocessor operator (2) . (3) :: (4) .* (5) ?
Except for the =, operator functions are inherited by any derived class;
however, any derived class is free to overload any operator.
Overloading Operators
When a binary operator is overloaded, the left operand is passed implicitly
to the function and the right operand is passed as an argument.
When a function returns the object that is associated with the operator, the
key word *this is used.
#include <iostream> coord coord:: operator + (coord ob2){
using namespace std; coord temp;
temp.x = x + ob2.x;
class coord {
temp.y = y + ob2.y;
int x, y;
return temp;
public:
}
coord(int i = 0, int j = 0) { x = i; y = j;}
void getxy(int &i, int &j) { i = x; j = y;} coord coord:: operator + (int i){
coord operator + (coord ob2); coord temp;
coord operator + (int i); temp.x = x + i;
coord operator ++ (); temp.y = y + i;
bool operator == (coord ob2); return temp;
coord operator = (coord ob2); }
}; coord coord:: operator ++ (){
bool coord:: operator == (coord ob2){ x++;
return x==ob2.x && y==ob2.y; y++;
} return *this;
}
Overloading Operators
coord coord:: operator = (coord ob2){
x = ob2.x; o1++.getxy(x,y);
y = ob2.y; cout << x: << x << y:<<y << \n;
return *this;
} ++o1.getxy(x,y);
int main(){ cout << x: << x << y:<<y << \n;
coord o1(10, 20), o2(5, 15), o3;
int x, y; if (o1 == o2) cout << Same\n;
o3 = o1;
o3 = o1 + o2; o3.getxy(x,y);
o3.getxy(x,y); cout << x: << x << y:<<y << \n;
cout << x: << x << y:<<y << \n;
return 0;
(o1 +100).getxy(x,y); }
cout << x: << x << y:<<y << \n;
Some Notes:
o3 = o1 + o2; o3.getxy(x,y); equivalent to (o1 + o2).getxy(x,y);
o1 and o2 do not change.
In the second case, the temporary object that is created to return the
object, is destroyed after the execution of (o1 + o2).getxy(x,y);
Overloading Operators
According to the early version of C++, the following two statements are
identical and use the same function:
++o1; o1++;
return o;
}
Using Friend Operator Function
Any modifications inside the friend operator function will not affect the
object that generated the call. To ensure changes, reference parameter is used.
return ob;
}