views:

135

answers:

3

Hi!

Let's say I have a class Point:

class Point {
    int x, y;
public:
    Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; }
};

Why can I not call this as such:

Point p1;
p1 += Point(10,10);

And is there any way to do this, while still having a reference as the argument?

+11  A: 

Why can I not call this as such:

Because you forgot to declare a matching constructor. Other than that, this call looks fine.

(Also, the code inside your operator += is wrong: it overwrites the values instead of doing additions).

Konrad Rudolph
Maybe he's not doing additions because he doesn't want to use the current values, which are undefined :)
Daniel Daranas
it's worth noting that a default constructor will also be needed.
markh44
@markh44: Compiler will provide a default constructor (though not a useful one). @Daniel not doing an addition in a += operation may be technically feasible but it is a logical error.
Martin York
Martin: yes, there's a default constructor – but only as long as no other constructor has been written manually, which is what Mark probably meant.
Konrad Rudolph
+5  A: 

You operator code is perfectly fine. You need to create a constructor which takes two ints:

class Point {
public:
  Point() : x( 0 ), y( 0 ) { }
  Point( int _x, int _y ) : x( _x ), y( _y ) { }
// rest of the code
};

Note that if you declare a constructor which takes some arguments then in order to make instantiation such as Point x; you need to declare a default constructor yourself.

P.S. Just read Konrad's answer. Yes, you might want to use += rather than = for your members. :)

sneg
+8  A: 

Here's the code you need:

class Point {
    int x,y;
public:
    Point(int x=0,int y=0) : x(x), y(y) {}
    Point& operator+=(const Point&p) {x+=p.x;y+=p.y;return *this;}
};

As Konrad pointed out, you need a constructor. Also you need to explicitly perform the additions inside your operator overload.

Dave Gamble
If you cut and paste the above code don't forget to add a semicolon after the constructor declaration.
Dave
I think that would be spurious...
Dave Gamble