C++

How do you implement operator overloading in C++ Programming2 min read

Operator overloading can be implemented in two ways. They are:

  1. Using a member function
  2. 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:

Output of the above program is as follows:

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:

Output of the above program is as follows:

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:

Output of the above program is as follows:

Take your time to comment on this article.

Leave a Comment