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

14th Dec 2023, 12:54 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 odpowiedzi
+ 2
17th Dec 2023, 7:04 AM
Bob_Li
Bob_Li - avatar
+ 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;
14th Dec 2023, 1:38 PM
Bob_Li
Bob_Li - avatar
0
Thanks but my concern is on return type of function. Does ref return is not mandatory for + operator ?
17th Dec 2023, 6:39 AM
Ketan Lalcheta
Ketan Lalcheta - avatar