Search code examples
c++referencethis-pointer

C++ class member function with reference return type


I am a newbie to programming and C++. I'm confused how reference works differently here.

The code below outputs 0 5 but removing the & from A &GotObj() would output 0 0. Why didn't the second case output 0 5?

Thanks in advance.

#include <iostream>
using namespace std;

class A {
public:
    int val;
    A(int n=0) {
        val = n;

    }
    A &GetObj() {
        return *this;
    }
};

int main() {
    A a;
    cout << a.val << endl;
    a.GetObj() = 5;
    cout << a.val << endl;
    return 0;
}

Solution

  • Case 1: A GetObj()

    • lets Create object of Class A :

    A a;

    • suppose this objects memory location is 0x87965432. Now, when you call function of object a by a.GetObj() then it returns a temporary object whose memory location will be completely different then Class A's object a, lets say 0x98672345. now if you assign value 5 by

    a.GetObj() = 5

    • then you are assigning value 5 to the object located at memory location 0x98672345. now, you are going to print val variable of object which is located at memory location 0x87965432. thats why it will print 0.

    Case 2: A &GetObj()

    • as explained in Case 1, if you create object by

    A a;

    • lets consider its memory location 0x87965432. now when you call function GetObj, by a.GetObj(), then return object will be of same memory location 0x87965432, as its concept of return by Referance. now assigning value 5 to this object,

    a.GetObj() = 5

    will reflect effect in object a. and now printing value of variable val will be as expected 5.