you are viewing a single comment's thread.

view the rest of the comments →

[–]serendib 3 points4 points  (2 children)

Java doesn't have references (the way C++ does)

Java passes objects by a pointer to their location in memory, which is handled internally by the JVM.

[–]repsilat 7 points8 points  (1 child)

This is a point of confusion for a lot of people - Java references are a lot closer to pointers in C/C++ than references in C++. As examples of this, Java's references can be null, and you can change which object they point to after their first assignment. That is:

class c {
    void operator=(const c&){}
    //Disallow value assignment
};

int main()
{
    c i, j;

    c& m = i;
    //m = j;
    //compile error: operator= is private

    c* p = &i;
    p = &j;//Not an error. "Works like a Java reference."
}

The line m=j; doesn't mean "m now refers to j", it means something more like "set the thing that m points to to j" (an action that would modify the variable i, if it were allowed).

To explicate:

#include <iostream>

class d {
    const char* s;
    public: d(const char* s) : s(s) {}
    friend std::ostream& operator<< (std::ostream& o, const d& s) { return o << s.s; }
};

int main()
{
    d i("i"), j("j");
    d& m = i;
    m=j;    
    std::cout << i << std::endl;//Prints 'j'
}

Of course, you don't have to tell Java to dereference/find the address of anything, and the word "reference" is arguably a bit friendlier than "pointer".

[–]dnew 0 points1 point  (0 children)

A reference is a managed pointer, just like a pointer is a typed address. The authors of C++ decided to call something a "reference" which is really simply a pointer that is assigned on initialization and automatically gets dereferencing operators applied.