0
#include<iostream>
using namespace std;

class mango
{
public:
    int qnt;
    mango(int x = 0)
    {
        qnt = x;
    }
    mango operator+(const int a)
    {
        mango temp;
        temp.qnt = a + this->qnt;
        return temp;
    }
};

int main()
{
    mango obj(5);
    obj = obj + 5;
    cout<<obj.qnt<<endl; // shows 10;
    return 0;
}

Now I want to overload object = constant_int + object, that is

obj = 5 + obj;

I want to keep constant integer on the left hand side and store the sum in the object. How to do that?

Aman Jain
  • 13
  • 3
  • You als have the opportunity to define a "free-standing" operator: `mango operator+(int, const mango&)`. If you need access to `protected` or `private` members, you can make it a `friend` of `class mango`. In this case, it even can be defined inline. – Scheff's Cat Dec 17 '20 at 06:46
  • If you implement operator `+` as a free function, it opens up extra possibilities, for example getting the behaviour you want. See [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) for some help on that and much additional wisdom. – user4581301 Dec 17 '20 at 06:46

1 Answers1

2

It's simple, define the overload out of class

class mango
{
    ...
};

mango operator+(const int a, const mango& b)
{
    ...
}

In fact it's generally reckoned that all symmetric and anti-symmetric operators should be defined out of class. So your mango + int should also be moved out of the class.

mango operator+(const mango& a, const int b)
{
    ...
}
john
  • 85,011
  • 4
  • 57
  • 81
  • Thanks, it works by declaring the function outside. I tried declaring the function inside and it shows error that I am allowed to pass only 0 or 1 arguments, why so? I declared the function as a friend and now it works. – Aman Jain Dec 17 '20 at 07:12
  • If you declare it inside (and not static or as a friend) then `this` is an implicit parameter. So your `operator+` would have three parameters which isn't allowed. – john Dec 17 '20 at 07:33