0

I've overloaded + operator for my custom class when the second argument is int. For example if my object is x, then x + 7 is possible while 7 + x is not. How can I make the latter possible?

I think including my class code is not necessary here.

  • Can I make it inside the class? –  Dec 02 '20 at 10:46
  • @jsk9 No, you can't add `operator+` for `int + custom object` in the class but for `custom object + int` it would work by adding `obj_type operator+(int) const` – Ted Lyngmo Dec 02 '20 at 10:48
  • @jsk9 See eerorika's answer. You usually define a free standing overload like that. – Ted Lyngmo Dec 02 '20 at 10:51
  • 1
    @TedLyngmo and eerorika: is this not an extremely clear duplicate of the thread I linked to above? I'm yet to receive a c++ gold badge so I cannot apply the dupe hammer here. – dfrib Dec 02 '20 at 10:54
  • @dfrib Though, answering such questions (instead of just flagging them as duplicate) could bring you closer to the C++ gold badge... ;-) – Scheff's Cat Dec 02 '20 at 10:56
  • @Scheff In this particular case I answered the exact same question yesterday (the linked thread is from yesterday and answered by myself), so that would be a tad bit too vampiric :D – dfrib Dec 02 '20 at 10:59
  • @dfrib This might have been the one where I added a close vote with the same link for duplicate... – Scheff's Cat Dec 02 '20 at 11:00

1 Answers1

1

Overloading operator + and doing a + b where a is int and b custom object

By defining the overload operator+(int a, custom b).

It may however be preferable to make the custom type implicitly constructible from int in which case you would only need one operator overload operator+(custom a, custom b) which would work with all combinations of custom and int.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • How to make the custom type implicitly constructible from int? –  Dec 02 '20 at 10:55
  • 1
    @jsk9 You add a converting constructor. `custom::custom(int x);` – Ted Lyngmo Dec 02 '20 at 10:57
  • Oh, ok. Btw seems like there is no way to keep it into the class right? Like I should define it outside. (I mean this operator overloading function). –  Dec 02 '20 at 11:00
  • 1
    @jsk9 If it is a friend function (and it typically has to be), then it can be defined within the class definition. But that's not necessary. – eerorika Dec 02 '20 at 11:03
  • I've added `operator+(custom a, custom b)` as well as converting constructor and erased the previous function `operator+(int n)`, still it does not work. It says that operator + is ambiguous. –  Dec 02 '20 at 11:15
  • Can templates be the reason? –  Dec 02 '20 at 11:19
  • @jsk9 Here's an [example](https://godbolt.org/z/8GMvWo) - If you have code that doesn't work you need to create question and include the code. Make a [mcve]. – Ted Lyngmo Dec 02 '20 at 11:27