Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a reference to a class data member and then trying to change that member

Tags:

c++

reference

I've seen other posts on this but didn't really get what happens yet.

so say i have this code:

template<typename T>struct S {
    S(T value):val{value}{}
    T& get(){return val;}
private:
    T val;
};
int main(){
S<int>s1{5};
int n = s1.get();
n = 10;
std::cout<<s1.get();
}

this prints: 5

my question is why if i returned a reference to val doesn't the value of val change when i changed the value of n?

like image 669
Daniel Avatar asked May 13 '19 17:05

Daniel


2 Answers

When you store the result in int n you create a copy. Try:

int &n = s1.get();
like image 103
Jeffrey Avatar answered Sep 29 '22 15:09

Jeffrey


If you do

int& n = s1.get();
n = 10;
std::cout << s1.get();

You will see 10.

like image 20
Tony Avatar answered Sep 29 '22 14:09

Tony