0
Why reference is not needed for + operator overloading
Hi Please refer attached code for reference. It's output is 9 which I expected. However, even if I change signature of operator + as below, test operator+(const test& other) It still works and gives 9 as output. Does reference return (test&) is not must for this operator and why ? https://sololearn.com/compiler-playground/ca5VNO2jSp44/?ref=app
3 Answers
+ 2
if you are mutating the value, then return by reference. if you are assigning to a new variable, then return by value.
https://stackoverflow.com/questions/2337213/return-value-of-operator-overloading-in-c
also
https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading
+ 1
using const reference as argument is better, I think:
test& operator+(const test& other){
m_x = m_x + other.m_x;
return *this;
}
allows you to use rvalues:
test obj1(2);
test res = test(3) + obj1;
compare this with:
test& operator+(test& other){
m_x = m_x + other.m_x;
return *this;
}
which will raise an error if you do the same:
test obj1(2);
test res = test(3) + obj1;
0
Thanks but my concern is on return type of function. Does ref return is not mandatory for + operator ?