Thread: change the target of a reference

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    change the target of a reference

    Hello everyone,


    I am shamed to ask this question because I can not figure out after some experiment. I think for reference variable, once it is binded, the target can not be changed.

    But why in my following sample, pi can be binded to a and later binded to b without any issues?

    Code:
    int main()
    {
    	int a = 10;
    	int b = 20;
    	int& pi = a;
    	pi = b;
    	
    	return 0;
    }

    thanks in advance,
    George

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    References can only be bound when they are initialised (which, in turn, is only possible when the reference is created).

    The assignment "pi = b" in your code does not bind the reference pi to b. It sets the value referenced by pi to the value of b (ie it sets a to the value of 20).

    If you want a rebindable reference, use a pointer. Assignment to a pointer (as long as you don't do any operations that dereference the pointer) changes what the pointer points at.

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    1,579
    Cool, grumpy!

    Quote Originally Posted by grumpy View Post
    References can only be bound when they are initialised (which, in turn, is only possible when the reference is created).

    The assignment "pi = b" in your code does not bind the reference pi to b. It sets the value referenced by pi to the value of b (ie it sets a to the value of 20).

    If you want a rebindable reference, use a pointer. Assignment to a pointer (as long as you don't do any operations that dereference the pointer) changes what the pointer points at.

    regards,
    George

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Makefile
    By pinkprincess in forum C Programming
    Replies: 3
    Last Post: 06-24-2007, 09:02 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  4. GCC - Strange networking functions error.
    By maththeorylvr in forum Windows Programming
    Replies: 3
    Last Post: 04-05-2005, 12:00 AM
  5. Replies: 2
    Last Post: 09-04-2001, 02:12 PM