Pointers and References (trying to clear some things up)

I know the difference between pointers and references, pointers point to the objects address in memory while references are another name for a variables.

Lets take a look at 2 examples:
1
2
  int i = 0;
  int *p = &i;


P points to i.

What about this?
1
2
 int i = 0;
 int &p = i;


I don't understand the second one, is p a reference to i? I thought references could only be on the right side?
In the first case &i returns the address of the variable i. So now p points to that address.


In the 2nd case you're creating an independent reference. p is a stand alone reference variable. They must be initialized when they are first declared as it must point to some object.
So in this case p indeed refers to i. And now p can be used in all the place i is used. Theres virtually no difference between the 2.

So basically you now have 2 names for the same variable.
Last edited on
I guess what confuses you is that & is used for two different things. They are not the same even though they both use the ampersand character. Whoever designed C++ could have chosen two different characters (but didn't for some reason) because the two uses have nothing in common.
Last edited on
Topic archived. No new replies allowed.