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;
}
Case 1: A GetObj()
A a;
a.GetObj() = 5
Case 2: A &GetObj()
A a;
a.GetObj() = 5
will reflect effect in object a. and now printing value of variable val will be as expected 5.