marco
marco

Reputation: 589

Operator overloading returning a reference

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 += ( ..?

Upvotes: 0

Views: 28

Answers (1)

Midren
Midren

Reputation: 409

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.

Upvotes: 1

Related Questions