class myClass
{
public:
int myVal;
myClass(int val) : myVal(val)
{
}
myClass& operator+(myClass& obj)
{
myVal = myVal + obj.myVa
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: