J
James Kanze
All references are pointers, but none are the kind of pointers usually
meant when discussing C or C++. For example in C and C++ if you have a
pointer p and do "p++;" that is an operation on the pointer. Whereas in
Java, if you have a reference r and do "r++;" that would be an operation
on the object r refers to [...]
So can we think of a C++ reference as:
Same as a pointer, 4 bytes.
No. The standard is very explicit; a reference doesn't have to
occupy any memory at all. (And the size of a pointer isn't
necessarily 4 bytes. For that matter, it isn't necessarily the
same for all pointer types.)
Since a reference isn't an object, and you can never obtain its
address, it's really irrelevant.
Same as a pointer, points to some where.
It designates an object. How it does so is up to the
implementation.
Main difference: with pointer, you can print out the pointer,
set the pointer to different values, including 0. With
reference, you can't. You always dereference a reference when
you use it.
That's a frequent way of thinking about it, and it may help
understanding. But formally, a reference is simply an lvalue
which refers to an object.
Here are some C++ and C code equivalent:
int a = 10; // In C: the same
int avg = 20; // In C: the same
int& b = a; // In C: int *pa = &a;
printf "%d", b; // In C: printf "%d", *pa;
b = 20; // In C: *pa = 20;
// can't do // In C: pa = (int *) 0; or (int *) NULL;
// can't do // In C: pa = &avg;
int& c = b; // In C: int *pa2 = &(*pa)
// &(*pa) is &(20) which is illegal
// but if it is C++, it magically
// changes &(*pa) to just pa
// So in C, int *pa2 = pa;
So In Java, Python, PHP5, and Ruby, when you use
a = Dog.new
it is really not a reference, not a pointer, but
something in between.
In C++ terminology, it's a pointer. The only difference is that
in Java (and I presume, the other languages as well), pointers
aren't a recognized object type, so you cannot to things with
them that you could do with an object type. (In Java, at least,
this is also the case for the basic types, such as int or
double.)
Not a reference, because you can set where it points to:
a = nil
Not a pointer, because you use
instead of a->bark() or (*a).bark()
That's just syntax.