Can I change a reference to another object?

Bruce Eckel writes in his c++ book:
Once a reference is initialized to an object, it cannot be changed to refer to another object. (Pointers can be pointed to another object at any time.)

I probably misunderstood, what limition is Bruce speaking of?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;
    

/*4. Write a function that takes a pointer argument, modifies what the pointer points to, and then returns the destination of the pointer as a reference.*/

int*& function(int*& taken) {
    (*taken)++;
    return taken;
}

struct Temp {
    int x;
    Temp() : x(88) {}
    ~Temp() {}
};

int main() {
    int x = 12;
    int q = 50;
    int& y = x;
    y=q; //works fine
    
    int* z = &x;
    cout << x << " " << y << " \n" << z << endl;
    cout << function(z) << endl;
    
    Temp Zz, Yy;
    cout << Zz.x;
    Temp& refZz = Zz;
    refZz = Yy; // works too
}


In my code it seems to work fine, while it shouldn't.. right?
Last edited on
From the description it sounds more like the function should be like this
1
2
3
4
int& function(int* taken) {
    (*taken)++;
    return *taken;
}



The Zz object is changed. The reference still refers to the same object.
1
2
Temp& refZz = Zz;
refZz = Yy; // works too 
Last edited on
hey Peter,

thanks,
(1) yes the function should be as you wrote. I made it like that first and then experimented around adding and removing * and & symbols to see if I understood it correctly.

(2) on topic: But Yy is another object than Zz right?
I also made int& y refer to x, and later made it refer to q. I thought this was supposed to not work ..?
What does Bruce mean?
Bruce is right. Doing refZz = Yy; is the same as doing Zz = Yy;. What happens is that Temp's copy assignment operator runs and copies the data of Yy to Zz. refZz still refers to Zz.
Last edited on
I also made int& y refer to x, and later made it refer to q.

No, you did not.

1
2
3
4
int x = 12;
int q = 15;
int& y = x; // This means that y is another name for x
y=q; // This means set the value of y (which is another name for x) to equal q. 

At this point, the value of x is 15. The value of y (which is another name for x) is 15. The value of q is 15.

1
2
// Now I change the value of y (which is another name for x)
y = 24;

At this point, the value of x is 24. The value of y (which is another name for x) is 24. The value of q is 15 - unchanged.

y=q; //works fine
It's the same as saying x=q.
Last edited on
Ah ok!! Thanks for clarifying.

I thought:
1
2
3
4
5
6
int main() {
    int x = 12, q = 88;
    int& y = x;
    y = q;
    cout << x;
}

would have output
12
but instead it's
88


It's clear now why, thanks!
Topic archived. No new replies allowed.