Re: References vs Pointers

"Stephen M. Webb" <[email protected]>
Newsgroups gmane.user-groups.linux.ottawa.general
Organization Xandros Corporation
Message-ID <[email protected]>
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.
-- 
OCLUG general discussion list
[email protected]
http://oclug.on.ca/mailman/listinfo/oclug
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.