Aman Jain
Aman Jain

Reputation: 41

How to overload object = constant int + object

#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?

Upvotes: 0

Views: 175

Answers (1)

john
john

Reputation: 87957

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)
{
    ...
}

Upvotes: 2

Related Questions