C++ Tutorial C++ Advanced C++ References

C++ - Unary Operator Overloading



Unary operators are those operators which acts upon a single operand to produce a new value. Following is the list of unary operators that can be overloaded in C++.

Overloadable unary operators in C++
+-*&
++--!~

The unary operators is used with object in the same way as it is used normally. The operator normally precedes object in the expression like - !obj, -obj, and ++obj but sometimes it can be used as postfix as well like obj++ or obj--.

Example: overloading unary minus (-) operator

In the example below, unary minus operator is overloaded. When it is used with vector object, it applies negation on x and y component of the object, for example - applying negation on (10, 15) will produce (-10, -15) and applying negation on (5, -25) will produce (-5, 25).

#include <iostream>
using namespace std;
 
class vector {
  public:
    int x, y;

    //class constructor
    vector(int x, int y) {
      this->x = x;
      this->y = y;
    }

    //function to display vector
    void displayVector() {
      cout<<"("<<x<<", "<<y<<")\n"; 
    }

    //function for overloading unary minus
    vector operator- () {
      x =  -x;
      y =  -y;  
      return vector(x,y);    
    }
};
int main (){
  vector v1(10, 15), v2(5, -25);

  -v1;
  v1.displayVector();

  -v2;
  v2.displayVector();
  return 0;
}

The output of the above code will be:

(-10, -15)
(-5, 25)

❮ C++ - Operator Overloading

5