1

This is a very basic operator overload question. Say I had a class like this...

class xy { public: double x, y; XY(double X, double Y) { x = X; y = Y;} XY operator+(const XY & add) const { return XY(this->x + add.x, this->y + add.y); } XY & operator+=(const XY & add) const {?} } } 

And I want operator+= do to what its supposed to do (you know, add to the current value of x and y). Wouldn't the code be the same for operator+ and operator +=?

2
  • I like this tutorial: cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html Commented May 21, 2011 at 19:00
  • I recommend the boost operators library for this sort of operator overloading. It allows you to define the minimal set of operations (+= in this case), and then automatically fills out the others (like operator +). Commented May 21, 2011 at 19:21

3 Answers 3

5

How could it be the same? They do different things.

If you don't care about optimizations you can use += in your + operator implementation:

XY operator + (const XY& right) const { XY left(*this); left += right; return left; } 
Sign up to request clarification or add additional context in comments.

3 Comments

As long as you declare these as inline functions (like they automatically are when defined inside the class) it should not even slow down the performance.
@leftaroundabout It depends on your copy constructor implementation. It might be faster to call the default constructor and construct the values manually.
Right. I was referring to this specific class with just two double variables, where default constructor + manual value assignment should not be faster than copy constructor. But of course this does not hold for all classes.
3

Yep, do the add operation (stick to the += operator), and return a reference to itself. Oh, and this can't be a const method.

XY & operator+=(const XY & add) { this->x += add.x; this->y += add.y; return *this; } 

1 Comment

haha that "const" was screwing me up when I tried to change anything pointed to by "this"
3

No. Conventionally, operator+ stores the result in a new object and returns it by value, whereas operator+= adds the right-hand side to *this and returns *this by reference.

The two operators are related -- and can often be implemented in terms of one another -- but they have different semantics and therefore can't have identical implementations.

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.