I would like to make a variable that points to whatever a different reference variable is pointing to, so that if I change where the reference variable points, the pointer variable automatically points to that new place, too.
For example, suppose I consider my favourite book to be whatever my local library's favourite book is. If my library changes what their favourite book is, I automatically consider that to be my favourite book.
Here is some code to demonstrate what I mean:
Book littleWomen = new Book("Little Women");
Book dracula = new Book("Dracula");
Book libraryFavourite = litteWomen;
Book myFavourite = libraryFavourite; //myFavoutie is now littleWomen
libraryFavourite = dracula; //i want myFavourite to update to point to dracula, now.
In the above code, changing what libraryFavourite
points to doesn't automatically change what myFavourite
points to. It stays pointing at littleWomen
.
I understand why the above code doesn't work as I'm saying I "want" it to. I understand that reference variables hold memory addresses, and therefore myFavourite = libraryFavourite
just assigns the memory address that libraryFavourite
points to into myFavourite
, and thus future changes to libraryFavourite
doesn't change myFavourite
. I only include the above code to help clarify the behaviour that I want, but understand I'll need a different approach to achieve.
This link talks about aliasing a class (and the answers received was basically that it can't be done). Aliasing isn't exactly what I want done, though, because I want to be free to change myFavourite
to stop pointing to the library's favourite book, and instead to something else (such as, for example, some new book that I newly discovered and fell in love with).