In Java and other high-level languages, a reference leads to an object.
In C++, as far as I know, a pointer can also lead to an object.
So what's the difference between a reference leading to an object, and a pointer leading to an object?
In Java and other high-level languages, a reference leads to an object.
In C++, as far as I know, a pointer can also lead to an object.
So what's the difference between a reference leading to an object, and a pointer leading to an object?
In my humble opinion it's almost just a conceptual difference.
With pointers
you handle the direct memory address. You can even make some operations, like iterate over it! It's clearly a low level
stuff. When you fulfill a pointer, you need a memory address. One like (very similar) the processor itself would receive. So, by definitions:
Pointers are variables who points to direct memory addresses.
Well, so I've been told in college! :D
With references
, on the other hand, the "language" make all the hard work for you! When you reference anything in a high-level language
you don't pass directly a memory address to the variable. You pass it, but as a reference, to a variable that you don't have to concern about being a pointer, reference, a int or what the hell you though that it'd be! (That part my vary between languages)
Pratically: Same goddamm thing!
Conceptualy: The references are a masked way to treat pointers.
They are very similar; they both do pointing to object instances in memory, but how the language lets you manipulate them is different.
In Java, a reference points to an instance of object in memory. You can reassign this reference so that it points to a different instance in memory at any time:
SomeObject ref = new SomeObject();
ref.doSomeWork();
...
ref = new SomeObject();
In C++, a reference cannot be reassigned to point to a different object -- it always points to the same memory location.
Pointers in C++ are more similar to Java references than C++ references are -- you can change which object they point to. They are also a bit more flexible than Java references, because you can manipulate the pointer itself, like incrementing it to point to another object in a list:
SomeObject* ptr = {instance1, instance2, instance3};
ptr->doSomeWork(); // calls instance1's doSomeWork method
ptr++;
ptr->doSomeWork(); // calls instance2's doSomeWork method
As @DennisBraga pointed out (pun), with pointers you get access to the memory address of the object, but with references (in Java) you don't. Also, with pointers you have to dereference it somehow to get at the object, but with Java references this happens behind the scenes for you.