Overload Unary Minus Operator in C++
Posted by Superadmin on August 08 2022 09:41:58

Overload Unary Minus Operator in C++

 

 

This C++ program overloads the minus(-) operator. The program defines a class and instantiates it. The minus operator is defined inside the class. The value of two objects can be subtracted using this operator.

 

Here is the source code of the C++ program which overloads the minus(-) operator. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to overload minus (-) operator
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Integer {
  8.     private:
  9.         int value;
  10.     public:
  11.         Integer(int v) : value(v) { }
  12.         Integer operator-(Integer i) {
  13.             value = value - i.value;
  14.             return *this;
  15.         }
  16. 	int getValue() { 
  17.             return value;
  18.         }
  19. };
  20.  
  21. int main()
  22. {
  23.     Integer a(10), b(20);
  24.  
  25.     cout << "a = " << a.getValue() << "\n";
  26.     cout << "b = " << b.getValue() << "\n";
  27.     cout << "a - b = " << (a -b).getValue() << "\n";
  28. }

 

$ a.out
a = 10
b = 20
a - b = -10