Operator overloading can be implemented in two ways. They are:
- Using a member function
- Using a friend function
Differences between using a member function and a friend function to implement operator overloading are as follows:
Overloading Unary Operators
Operators which work on a single operand are known as unary operators. Examples are: increment operator(++), decrement operator(–), unary minus operator(-), logical not operator(!) etc.
Using a member function to overload an unary operator
Following program demonstrates overloading unary minus operator using a member function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; class Number { private: int x; public: Number(int x) { this -> x = x; } void operator–() { x = –x; } void display() { cout << “x = “ << x; } }; int main() { Number n1(10);– n1; n1.display(); return 0; } |
Output of the above program is as follows:
1 2 3 | x = –10 |
In the above program the value of x is changed and printed using the function display(). We can return an object of class Number after modifying x as shown in the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> using namespace std; class Number { private: int x; public: Number(int x) { this -> x = x; } Number operator–() { x = –x; return Number(x); } void display() { cout << “x = “ << x << endl; } }; int main() { Number n1(10); Number n2 = –n1; n2.display(); return 0; } |
Output of the above program is as follows:
1 2 3 | x = –10 |
Using a friend function to overload an unary operator
When a friend function is used to overload an unary operator following points must be taken care of:
- The function will take one operand as a parameter.
- The operand will be an object of a class.
- The function can access the private members only though the object.
- The function may or may not return any value.
- The friend function will not have access to the this
Following program demonstrates overloading an unary operator using a friend function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> using namespace std; class Number { private: int x; public: Number(int x) { this -> x = x; } friend Number operator–(Number & ); void display() { cout << "x = " << x << endl; } }; Number operator–(Number & n) { return Number(–n.x); } int main() { Number n1(20); Number n2 = –n1; n2.display(); return 0; } |
Output of the above program is as follows:
1 2 3 | x = –20; |
Take your time to comment on this article.