user975989
user975989

Reputation: 2648

Reference to reassigned variable

Say I have a this code:

class A{
    ...
};

//somewhere else
A a;
A & ref = a;
a = A();

Does ref still reference the a? Regardless of how many assignments happen? That is, the assignment operator would never cause a memory location change, right?

Upvotes: 1

Views: 93

Answers (3)

user2736738
user2736738

Reputation: 30926

Yes it does so. Actually after the last line ref will point to whatever a points to.

Whatever you do to the reference is also done to the original object.

So all you do is defining an alternative name for the same variable.

There are few things you need to remember

i) references are different from pointers

ii) pointer may be undefined /null but reference should always be associated with a variable.

iii) pointer may be able to point to different variable at different time; reference always associated with the same variable throughout it's life. Check this question

Upvotes: 2

Andreas DM
Andreas DM

Reputation: 10998

Does ref still reference the a?

Yes.


A reference variable is an alias for another variable.
ref is bound to a, to it's original variable memory. Assigning something to a will also affect ref since it refers to the memory of a. Below is a small example:

class A {
public:
    A(int x, int y) : m_x(x), m_y(y) {}
    A() = default;
    int m_x;
    int m_y;
};

int main()
{
    A a;
    A &ref = a;

    a = A(500, 500);

    cout << ref.m_x << " " << ref.m_y << endl;
}

Output is 500 500

Upvotes: 0

wizurd
wizurd

Reputation: 3729

Does ref still reference the a?

Yes . Look at the code below. It shows how the assignment does not change the memory location...

A a;
std::cout<<"a:"<< &a<<std::endl;
A & ref = a;
std::cout<<"ref:"<< &ref<<std::endl;

a = A();
std::cout<<"a:"<< &a<<std::endl;

The output looks like so:

a:0x7fffaaa5fcaf
ref:0x7fffaaa5fcaf
a:0x7fffaaa5fcaf

Upvotes: 2

Related Questions