Both Java and C++ have references.
Are they practically the same or are they significantly different?
Java has no pointers. So are references in Java like pointers in C++?
Are there code structures around references and pointers that are the same in the two languages but do different things?
For a senior C++ programmer, the best way to explain java, or part of java, is to say:
A very common source of confusion is thinking that references in Java and C++ are similar because they have the same name. This is indisputably false.
Consider a C++ or Java class called Dog with a constructor that supports a name and getName and setName methods.
In Java this code that uses references is valid:
The same code in C++ using references does not compile and when it compiles (removing the lines marked with
!!!
) it does different things than in Java :The same code in C++ with pointers would be valid and does the same as in java.
Java references are also very different from C++ references when it comes to parameter passing.
C++ references also don't make aDog refer to another object, but unlike in Java, it does change the contents of
unPerro
enmain
as a consequence of how the assignment operator works (assuming a normal implementation of the assignment operator):In the case of arguments passed by pointer in C++ it has the same effects as in Java, since pointers in C++ are also passed by value, just like Java references:
So far Java references look a lot like C++ pointers and are very different from C++ references.
But there are also important differences between pointers in C++ and references in Java:
delete
so they don't occur.Without going around too much, in Java everything is passed by value. The reason objects seem to be passed by reference is because actually when you pass an object as a parameter you are actually passing the value of the address in memory it points to, this is why you can change the properties of the object by its address, but if you try to re-instantiate, the address will be lost and a new one (from the recent instantiation) will be assigned.