Daniel
Daniel

Reputation: 69

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

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?

Upvotes: 5

Views: 115

Answers (2)

Tony
Tony

Reputation: 652

If you do

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

You will see 10.

Upvotes: 5

Jeffrey
Jeffrey

Reputation: 11430

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

int &n = s1.get();

Upvotes: 5

Related Questions