English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Overloading unary operators

C++ Operator Overloading and Function Overloading

Unary operators operate on only one operand, here is an example of a unary operator:

Unary operators usually appear on the left side of the object they operate on, such as !obj,-obj and ++obj, but they can also be used as postfix, such as obj++ or obj--.

The following example demonstrates how to overload the unary minus operator ( - )

#include <iostream>
using namespace std;
 
class Distance
{
   private:
      int feet;             // 0 to infinity
      int inches;           // 0 to 12
   public:
      // Required constructor
      Distance()
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      // Method to display distance
      void displayDistance()
      {
         cout << "F: " << feet << " I:" << inches << endl;
      }
      // Overloaded negative operator ( - )
      Distance operator- ()  
      {
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
};
int main()
{
   Distance D1(11, 10), D2(-5, 11);
 
   -D1;                     // Negate
   D1.displayDistance();    // Distance D1
 
   -D2;                     // Negate
   D2.displayDistance();    // Distance D2
 
   return 0;
}

When the above code is compiled and executed, it will produce the following results:

F: -11 I:-10
F: 5 I:-11

I hope the above examples help you better understand the concept of unary operator overloading. Similarly, you can try to overload the logical NOT operator (!).

C++ Operator Overloading and Function Overloading