7stud -- wrote:

> A C++ reference, which is a different type than a pointer in C++, is 
> actually implemented as a pointer behind the scenes.  However, C++ 
> references allow you to use a different syntax that doesn't require 
> dereferencing:
> 
> int x = 10;
> int& r = x;  //r becomes a pointer to the same address as x
> r = 5;
> 
> cout<<x<<" "<<r<<endl;  //5 5


I am starting to see what pointer and reference are and how they relate 
to each other.

in the C era, a pointer *is* a reference.  that's why when we have

int a = 10;
int *pi = &a;

and you can "dereference it":

*pi = 20;

Until when C++ comes along, then we have a new "reference":

int a = 10;
int i =& a;    // or int i = &a;  i am not sure about the syntax.
i = 20;        // now both a and i are 20

so this type of reference is an implicit pointer...  it points to a, but 
you don't use the way in C  (int *pi = &a)  And when you use (i = 20), 
it does the dereference silently.  (*pi = 20;)

so a reference is new: a pointer but "looks like not a pointer".

come to think about it, in Java and Ruby, they are like that too.

a = Car.new

a doesn't look like a pointer, but it is actually a pointer.

we don't dereference it to get to the attributes like (*a).value = 10
or a->value = 10   but just use  a.value = 10

So from this point on, a reference and a pointer are not the same... a 
reference is a pointer "that doesn't look like a pointer."

they both points to something.  but the syntax (or grammar) of usage 
doesn't look like it is a pointer in the C era.  a reference is an 
"automatically dereferenced" pointer, shall we say?  or an "implicit" 
pointer, or "silent" pointer.
$a = 10;
$b =& $a;    # now $b implicitly points to $a
$b = 20;     # now $b implicitly points to $a, which is 20

$a = new Foo("hello");  # $a implicitly points to a Foo object
                        # the Foo object is 100 bytes,
                        # but $a is just 4 bytes

$b =& $a;    # $b implicitly points to $a.
             # $b is a pointer to pointer
             # $b points to a four byte pointer, which is $a

$b = new Foo("ok");   # dereference $b and sets its content to
                      # a new pointer to another object Foo("ok")
                      # that is, $a points to Foo("ok") now
                      # $b still points to $a, which points to Foo("ok")

So now, when you print $b and $a, they are both Foo("ok")

So now gets back to Ruby, do we have something like the above

a = 10
b = ____lineA1_____
b = ____lineA2_____

and now b implicitly points to a, which implicitly points to something 
else, not 10 any more.

similarly

a = Dog.new
b = ____lineB1_____
b = ____lineB2_____

and now b implicitly points to a, which implicitly points to something 
else, not the original Dog.new object any more.

Do we have that in Ruby?



-- 
Posted via http://www.ruby-forum.com/.