class OpClass
{
private:
int x;
public:
// declare operator+ - i.e. OpClass + OpClass
// this function will be returning a copy since the expression
// z = x + y does not modify x or y
OpClass operator+(OpClass right); // should really be const!
};
OpClass OpClass::operator+(OpClass r)
{
// this part is actually garbage.
OpClass sum;
sum.x = this->x + r.x;
// or sum.x = x + r.x;
return sum;
}
and here's how it's done properly:
class OpClass
{
private:
int x;
public:
// always perform binary operations in terms of +=, -=, *= etc
OpClass& operator+=(const OpClass& r) {
x += r.x;
return *this;
}
};
// define binary operators in terms of unary
OpClass operator+(OpClass l, const OpClass& r)
{
// note that the l argument is implicitly a copy
l.x += r.x;
return l;
}