1

In c++ we use & to represent pass by reference. Since objects are always passed by reference you do not need to use this &? Or does it not matter?

How do java and c++ differ in pass by value and reference. Everything in java I thought is pass by reference but it is pass by value? Why is this? So is it primitives are pass by value while class objects are pass by reference?

1
  • This answer to a different question probably contains most of what you want to know. Commented Jan 6, 2011 at 9:19

2 Answers 2

8

Clear two things up:

  1. C++ default is pass by value always, and you explicitly have to indicate if your function accepts a reference with the &
  2. Java is pass by value always (objects are not passed by reference, but the reference is passed by value - i.e. it's a copy of the reference to the object - hence you can modify the object using that reference but you can't expect operations like swaps[one reference with another] to work correctly)
Sign up to request clarification or add additional context in comments.

1 Comment

It's helpful to consider all object variables in Java as equivalent to C++ pointers. That is how they are handled.
0

I wrote a detailed answer before on the C++ argument passing semantics that include a final section on how Java semantics differ. You can read it here

Basically, and taking arrays aside (more on arrays here), as those are a different beast. In C++ if the argument type does not contain & it is passed by value (copied). If the type contains a * then it is a pointer, and it is the pointer the one that gets copied, but a copy is performed.

In Java, with reference types you never work with the actual object but with references to it (pointers in C/C++ dialect). All arguments are passed by value, which means that the reference will get copied (the function will not be able to modify the caller's reference) but the referred object can be modified through the copied reference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.