i have been given class with int variables x and y in private, and an operator overload function,
class Bag{
private:
int x;
int y;
public:
Bag();
~Bag();
//.......
//.....etc
};
Bag operator+ (Bag new) const{
Bag result(*this); //what does this mean?
result.x += new.x;
result.y += new.y;
}
What is the effect of having “Bag result(*this);” there?.
Bag result(*this)creates a copy of the object on which the operator function was called.Example if there was:
then
resultwill be a copy ofop1.Since the
operator+function is doing a sum of its operands and returning the sum, we need a way to access the operand op1 which is done through thethispointer.Alternatively we could have done: