| Author |
Objects, unsure how this works.
|
colin shuker
Ranch Hand
Joined: Apr 11, 2005
Posts: 712
|
|
Hi, I have an array of Cube objects: I also have a method which swaps the positions of some of the Cube's in the array So this code works, but I'm not sure why: Since 'temp' refers to cubes[a], then when we set cubes[a] to cubes[b], shouldn't temp then reference cubes[b]. It doesn't seem to, temp is set cubes[a], then it appears to be fixed, even when we change the value of cubes[a], Can anyone clarify this. Thanks
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
Remember that cubes[a] and cubes[b] are just references. In this code, you can read this as 1. Make temp point to the object that cubes[a] is pointing to. 2. Make cubes[a] point to the object that cubes[b] is pointing to. 3. Make cubes[b] point to the object that cubes[c] is pointing to. 4. Make cubes[c] point to the object that cubes[d] is pointing to. 5. Make cubes[d] point to the object that temp is pointing to. So in line 1, you would have temp, cubes[a] ===> object 1 cubes[b] ===> object 2 In line 2, you would have temp ===> object 1 cubes[a], cubes[b] ===> object 2
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9955
|
|
I have an array of Cube objects
No, you really don't. you have an array of REFERENCES to cube objects. the cubes live off somewhere in the heap. your array holds (effectivly) a bunch of pointers to those objects. Think of the array as a bunch of index cards, each having someones home address written on it. when you say Cube temp=cubes[a]; you are writting the address that is on cubes[a] on a new index card called 'temp'. cubes[a] = cubes[b] simply erases the old address on that card, and writes the new address on it. the contents of the house never change. the address written on your 'temp' card doesn't change.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
colin shuker
Ranch Hand
Joined: Apr 11, 2005
Posts: 712
|
|
|
Excellent, both great explanations, that clears it up.
|
 |
 |
|
|
subject: Objects, unsure how this works.
|
|
|