In this article we will discuss how to overload unary operators in c++ using both member and Friend function.

What is an unary operator?

An Unary operator is an operator that operates on a single operand and returns a new value.

Some of the unary operators are,

  • ++ (Increment Operator)
  • —   (Decrement operator)
  • –    (Unary Minus operator)
  • !    (NOT Operator)

etc.

For primitive types like int and string etc, these unary operators are already overloaded. Let’s see how to overload a unary operator for a User Defined class.  

Overloading Unary Operators for User Defined classes

Suppose we have class that represents a Complex Number i.e it has 2 ints as member variables i.e.

Now let’s overload Unary Minus operator ( – ) for this class. For that we need to create an – operator function in class ComplexNumber.

Operator overloading can be done in 2 ways i.e.

  • By Creating Operator function as member function of class
  • By Creating Operator function as global friend function.

Overload Unary Minus (-) Operator using class Member function

Unary operator acts on one operand only. In case overloaded operator function is a class member function, then it will act on the object with which it is called and use it as operand. Hence we need not to pass any extra argument in unary operator function if its class member function.

Let’s see how to overload Unary Minus ( – ) operator for above class i.e.

It returns a new object with modified values.

Checkout complete example as follows,

Output:

Overload Unary Minus (-) Operator using Global Friend Function

As unary operator acts on one operand only and in case if we are making operator function global, then we need to pass the operand as argument i.e.

And as above global function is accessing private data members of class ComplexNumber, so we need to make it friend of class ComplexNumber i.e.

It returns a new object with modified values.

Complete example is as follows,

 

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.