0

I am trying to understand what is the real deal with returning a reference, while studying operator overloading. I create this very simple problem:

#include <iostream>
using namespace std;
class mydoub {
 public:
 double pub;
 mydoub(double i = 0) : pub(i) {}
};
mydoub &operator += (mydoub &a, double b) {
 a.pub = a.pub+b;
 return a;
}
int main() {
 mydoub a(5), b(6);
 cout << "1: " << a.pub << " " << b.pub << endl; // expected output 1: 5 6
 b = a+= 7;
 cout << "2: " << a.pub << " " << b.pub << endl; // expected output 2: 12 12
 b.pub = 8;
 cout << "3: " << a.pub << " " << b.pub << endl; // unexpected output: 3: 12 8
}

The output is:

1: 5 6
2: 12 12
3: 12 8

which is quite unexpected to me. In fact, b has been assigned a reference to a, right after the latter has been modified, so I expect b.pub=8 to act on a as well, as a result of the reference passing through the operator +=. Why isn't it so? What is then the difference with a non-reference overload, say mydoub operator += ( ..?

asked Mar 29, 2020 at 11:28

1 Answer 1

1

You are messing with an understanding of reference. Reference, in fact, is just dereferenced pointer and when you do b = a, it is actually copying the a value to b, they are not pointing to the same object. To point to the same object you need to use pointers or make b not mydoub type, but mydoub& type (in that case, while initializing you can point to the same object).

mydoub& operator += is used to can modify the result of += operator. For example,

mydoub a = 1;
++(a += 3)

After that a will 5, but if you use mydoub operator += it will be 4.

answered Mar 29, 2020 at 11:37
Sign up to request clarification or add additional context in comments.

3 Comments

so, are you saying that passing by reference is equivalent to provide some sort of temporary pointer to what I am returning, but just within the scope of the return statement?
It just returns the equivalent of the temporary pointer but dereferenced. As a result, references cannot be null.
Ok, thank you very much, I think I know what you mean now, and it all makes sense to me

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.