const function operator+(const function *) const;
What will happen if you do: x += y;
...when x and y are of the same class. Does it still work in this context or does it have to be x + y;
?
const function operator+(const function *) const;
What will happen if you do: x += y;
...when x and y are of the same class. Does it still work in this context or does it have to be x + y;
?
In order for +=
to work for a user defined type, it has to be overloaded. This is independent of whether operator+
has already been overloaded for that type. There is no automatic generation of arithmetic operators based on other ones1.
Note that the usual strategy is to overload operator+
as a non-member, in terms of operator +=
. For example,
struct Foo
{
int i;
Foo& operator += (const Foo& rhs)
{
i += rhs.i;
return *this;
}
};
Foo operator+(const Foo& lhs, const Foo& rhs)
{
Foo result = lhs;
result += rhs;
return result;
}
Note: The latter operator is often expressed as a one or two-liner (see for example SO's own operator overloading wiki. But that inhibits return value optimization for little gain. I have chosen a more verbose implementation here to avoid that pitfall, without incurring any loss in clarity.
1 Attempts at solving this "problem" are boost operators
and the broken std::rel_ops
They are distinct and unrelated (as far as compiler is concerned)
Though, if you overload 1 of them, it is probably worth also overloading the other for consistency
btw. Here is very good explanation of operator overloadings: https://stackoverflow.com/a/4421719/3595112
If you want to support +=
, you need to overload operator+=
to do so. Just overloading +
and/or =
is not sufficient.
Boost operators does support this though. Basically, you provide overloads of a very minimal set of operators, and it fills in the holes using those.
It won't work, and end up in error. If you want to make +=
to work, you'll need to overload that operator too, overloading +
only isn't enough.