0
class myClass
{
public:
    int myVal;
    myClass(int val) : myVal(val)
    {

    }
    myClass& operator+(myClass& obj)
    {
        myVal = myVal + obj.myVal;
        return *this;
    }
    myClass& operator+(int inVal)
    {
        myVal = myVal + inVal;
        return *this;
    }
    myClass& operator=(myClass& obj)
    {
        myVal = obj.myVal;
        return *this;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    myClass obj1(10);
    myClass obj2(10);
    obj1 = obj1 + obj2;
    obj1 = 20 + obj2; // Error : No matching operands for operator "+"
    return 0;
}

How can I implement operator '+' on integer and myClass object types as operands? (obj1 = 20 + obj2)

ScarCode
  • 3,074
  • 3
  • 19
  • 32
  • 1
    Well declaration would look like this: myClass operator+(int v, myClass const& obj). You would also have to declare operator as a friend of class myClass or make your class members public (not recommended) – mateeeeeee Nov 30 '20 at 15:14
  • 1
    Does this answer your question? [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) – Scheff's Cat Nov 30 '20 at 15:17
  • Thanks alot to both of you!. – ScarCode Nov 30 '20 at 15:25

1 Answers1

4

You typically implement the binary arithmetic += (compound-assignment) operator as a member function, and + as a non-member function which makes use of the former; this allows providing multiple overloads of the latter e.g. as in your case when the two operands to the custom binary arithmetic operators are not of the same type:

class MyClass
{
public:
    int myVal;
    MyClass(int val) : myVal(val) {}
    
    MyClass& operator+=(int rhs) {
        myVal += rhs;
        return *this;
    }
};

inline MyClass operator+(MyClass lhs, int rhs) {
    lhs += rhs;
    return lhs;
}

inline MyClass operator+(int lhs, MyClass rhs) {
    rhs += lhs;
    return rhs;
    // OR:
    // return rhs + lhs;
}

int main() {
    MyClass obj1(10);
    MyClass obj2(10);
    obj1 = 20 + obj2;
    obj1 = obj1 + 42;
}

For general best-practice advice on operator overloading, refer to the following Q&A:

dfrib
  • 70,367
  • 12
  • 127
  • 192