So I saw a video talking about operator overloads in a class. This class was a fictitious Number
class which instantiated real numbers and could be used like this Number first(1)
or Number second(2)
(numbers are stored in a num data member) and then we overloaded the operators as member methods , to be able to do this first + second
or -first
. The code for these operator overloads looked like this:
PS: rhs
for right hand side
Number &Number::operator+(const Number &rhs) {
//perform math calculation between both objects
return *this; //return lhs by reference
}
or this for the unary minus operator which just returns the minus version of a single integer (useless but used as an example):
Number operator-() {
int temp = -num;
return temp;//temporary
}
Now the video said that we should return an object by reference if it was used in a chain operations after it has gone throught the overload, I also heard it depends of the performance (is it to avoid copying?), but after that I'm still unsure when to return an object by reference or not in class operator overloads.
Thanks in advance.