Overload unary minus operator in C++?


The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.

The unary operators operate on a single operand and following are the examples of Unary operators −

  • The increment (++) and decrement (--) operators.
  • The unary minus (-) operator.
  • The logical not (!) operator.

The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--.

Following example explain how minus(-) operator can be overloaded for prefix usage −

Example

#include <iostream>
using namespace std;
class Distance {
   private:
   int feet;
   int inches;
   public:
   // Constructor
   Distance(int f, int i) {
      feet = f;
      inches = i;
   }
   // method to display distance
   void display() {
      cout << "F: " << feet << " I:" << inches <<endl;
   }
   // overloaded minus(-) operator
   Distance operator-() {
      feet = -feet;
      inches = -inches;
      return Distance(feet, inches);
   }
};
int main() {
   Distance D1(3, 4), D2(-1, 10);
   !D1;
   D1.display();
   !D2;
   D2.display();
   return 0;
}

Output

This will give the output −

F: -3 I:-4
F: 1 I:-10

Updated on: 11-Feb-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements