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?
#include <iostream>
usingnamespace 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?
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.
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.