Well, in both Java and C++, there are two options when passing arguments: Pass by Value(PbV) and Pass by Reference(PbR).
Java pass all preliminary objects by value, and pass all other objects by reference.
While C++ pass everything by value unless you require to pass by reference.
- Pass by Value
In both Java and C++, pass by value is to make a copy of the passed object, what you do in the function to the object will not have any influence on the original object outside the function.
e.g.,
void foo(aTemp)
{
aTemp = 2;
}
....
int a = 1;
foo(a)
std::cout << a;
The output will be 1;
- Pass by Reference
Pass by reference does not make a copy of the object, it makes a copy of the reference of the object.
e.g.
void foo(&aTemp)
{
aTemp = 2;
}
....
int a = 1;
foo(a)
std::cout << a;
The output will be 2.
- More Complicated Situation
So far, there is no big difference between java and c++. However, if you assign passed-in object to a new one, the situation will be different.
e.g.
in C++,
void foo(&aTemp)
{
myClass b(2);
aTemp = b;
}
...
myClass a(1);
foo(a)
std::cout << a;
The output will be 2.
However, in Java
void foo(aTemp)
{
myClass b = new myClass(2);
aTemp = b;
}
...
myClass a = new myClass(1);
foo(a)
std::cout << a;
The out put will be 1.
The different output here is caused by the difference in "=" in java and c++.
In c++, if you do not override "=" in a irregular way, the value of myClass b will be copied into aTemp which points to a.
While in Java, when you do aTemp = b, you assign the address of object b to aTemp, so aTemp no longer points to the original a, and no matter what you do to aTemp, it has no long influence on a.
So in summary, all arguments in Java and C++ are passed by value -- value of the object or value of the reference -- the difference only lays on how you manipulate the value.
This is what I learned from my normal work, hope this helps.