Aaron
Aaron

Reputation: 21

Can C++ reference refer to another object?

I learned that once a reference is initialized to an object, it cannot refer to another object. I wanted to try that myself. This is what I tried:

struct X
{
    int s;
};

int main()
{
    X x1;
    X x2;

    X& xRef = x1;
    xRef = x2;

    X* xPtr = &x1;
    xPtr = &x2;
}

This code compiles without problems. Why is that? Am I missing something?

Upvotes: 0

Views: 452

Answers (1)

cdhowie
cdhowie

Reputation: 169008

It compiles because it is valid C++, it just doesn't happen to do what you think it does.

xRef = x2;

This line does exactly the same thing as:

x1 = x2;

Because xRef is a reference to x1 you are actually assigning the value of x2 to x1.

For example:

int a = 5;
int b = 6;

int & a_ref = a;
a_ref = b;

b = 7;

std::cout << "a:" << a << " b:" << b << std::endl;

This will show that the value of a is 6 (due to the line a_ref = b;) and b is 7.

The C++ language does not contain any mechanism by which you can rebind a reference. Once bound, a reference only ever refers to the same object and this cannot be changed.

Upvotes: 3

Related Questions