Reputation: 3
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;
}
Upvotes: 0
Views: 2077
Reputation: 5233
This of a reference as just a pointer with a slightly different syntax.
When GetObj
is defined as
A& GetObj() { return *this: }
it returns a reference (i.e. a pointer) to a. Then, the assignment
a.GetObj() = 5
effectively invokes the assignment operator of a
with the argument 5, which changes the value of a to 5.
But if you define GetObj()
as
A GetObj { return *this; }
it returns a completely new temporary object that has the same value as a. So when you later assign 5 to it, it doesn't change the value of a.
Upvotes: 1
Reputation: 136
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.
Upvotes: -1
Reputation: 145279
When you return by value the expression a.GetObj()
just creates a temporary. Assigning then only changes the value of that temporary.
Upvotes: 1