[oclug] References vs Pointers

Stephen M. Webb stephenw at xandros.com
Wed Jul 2 17:27:04 EDT 2008


On 02/07/08 17:07, Jon Earle wrote:
>
> Now, I was under the impression that references were just a fancy word for
> pointers, ie: a reference is an address of an object.  So, why can I not
> assign the reference to a pointer variable?  Missing something, not sure
> what.

In C++, a reference is not just a fancy word for a pointer.  It's an entirely 
different beast with entirely different semantics.

If you want to assign an rvalue (like the X parameter in your setval function) 
to the address pointer to by a pointer, you need to apply the "dereference" 
operator to obtain the desired lvalue.  Perhaps that's the source of your 
confusion?

void setval(myclass obj, int& x)
{
  *obj.i = x;
}

Or, alternatively, depending on what semantics you desire,

void setval(myclass obj, int& x)
{
  obj.i = &x;
}

In the first example, the value of "j" will be assigned to wherever mc.i 
points (in your code, this will invoke undefined behaviour and unleash 
starved lions on certain parts of PEI, or maybe crash).  In the second 
example, mc.i will contain the address of j.


More information about the OCLUG mailing list