3
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;?

1
  • 4
    Nothing will happen unless you overload += for your class. Also, your + operator will probably not work, because it expects a pointer on the RHS. Commented May 2, 2014 at 5:40

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately the operator+= implementation in the operators wiki is sub-optimal. I may change it later.
3

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

Comments

0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.