-1

is it possible using operator overloading to change the behavior of minus operator on integers in C++?

2 Answers2

1

No, you can't overload your own operators for intrinsic data types.


You can however create your own class / struct to represent an integer type and overload the operator-() for that one:

struct MyInt {
    int i;

    int operator-() { return +i; }
};
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

No! If you want to overload an operator, the argument of your operator must contain at least one user-defined type. For example, in this case, you can overload minus for an integer and a class.

  • Probably just a terminology mixup but "If you want to overload an operator, the argument of your operator must contain at least one user-defined type" is not strictly true. `int main(void) { class Integer{ int _data = 0; public: Integer& operator+(int term/*non user defined param*/) { _data += term; return *this; } }; Integer someInt; someInt + 5/*non user defined argument*/; }` – George Sep 01 '18 at 09:14
  • @George Yes, you're right. I didn't want to go to the detail of operator overloading. As you said, they are two ways to overload an operator. The first way that you mentioned is to introduce it as a thing that operates on an object of the class. Here it means for a given object of a class this is like obj.operator-(int) but here again, we're modifying operator on the class, not in the general. The second way as I mentioned in my answer is to define the operator independent of the object. That it is some sort of a function that it takes one integer and another object of the class. – Amir Tavakkoli Sep 01 '18 at 09:43