From the examples I have seen when people use the operator+
when adding two instances of a class, the usual pattern is to return an object. Suppose we have a Vector
class with attributes u
and v
, an implementation of operator+
could be,
Vector2 Vector2::operator+(const Vector2& other) {
return Vector2(this->u + other.u, this->v + other.v);
}
Why is the standard pattern not to return a reference? This is returning an object that was created on the Stack, this means that it should be garbage collected later on when we leave the function and could lead to problems from what previously pointed to it. e.g.
Vector2 v = Vector(10,20) + Vector(30, 40)
, would v
later be pointing to a garbage collected variable? Because the result of Vector(10, 20) + Vector(30, 40)
was created on a Stack (That we have now left).
What I am saying is, why should this not be something like,
Vector2* Vector2::operator+(const Vector2& other) {
return new Vector2(this->u + other.u, this->v + other.v);
}