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

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
lejit158
  • 27
  • 3
  • 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. – juanchopanza May 02 '14 at 05:40

4 Answers4

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

Community
  • 1
  • 1
juanchopanza
  • 216,937
  • 30
  • 383
  • 461
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

Community
  • 1
  • 1
industryworker3595112
  • 3,078
  • 1
  • 13
  • 18
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.

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
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.

Sufian Latif
  • 12,648
  • 3
  • 32
  • 70