Your code would look like:
class Bag {
public:
Bag();
Bag(Bag const& other); // copy ctor, declared implicitly if you don't declare it
~Bag();
Bag operator+(Bag const& other) const;
private:
int x;
int y;
};
Bag Bag::operator+(Bag const& other) const {
Bag result (*this);
result.x += other.x;
result.y += other.y;
return result;
}
The implicit "current object" for member functions is pointed to by a special value named this. Then *this
gets that object (by dereferencing this), and it is used to construct (via the copy constructor) another Bag named result.
I suspect this code is taken from a homework assignment, so you might not be able to use the one true addition operator pattern, but it is common and you should be aware of it:
struct Bag {
//...
Bag& operator+=(Bag const& other) {
x += other.x;
y += other.y;
return *this; // return a reference to the "current object"
// as almost all operator=, operator+=, etc. should do
}
};
Bag operator+(Bag a, Bag const& b) {
// notice a is passed by value, so it's a copy
a += b;
return a;
}