In Java, all variables containing proper objects are actually references (i.e. pointers). Therefore, method calls with these objects as arguments are always "by reference". Calling a method which modifies the state of the object also affects the original object (on the caller side).
C++ is different: Here arguments can be passed by value or passed by reference. Calling a mutator method on an object which was passed by value leaves the original object unaffected. (I suppose call by value creates a local copy of the object).
So my first response to this - coming from Java to C++ - is: ALWAYS use pointers when using objects as arguments. This gives me the behavior I have come to expect from Java.
However, one could also use "call by value" in case one does not need to modify the object in the method body. Are there reasons why one would want to do this?
ALWAYS use pointers when using objects as arguments
No, in C++ always pass by reference, unless your function can be called with nullptr
as a valid argument. If the function does not need to modify the argument, pass by const
reference.
Passing arguments by value has several uses.
If your function needs to create a copy of the argument it is better to create this copy by passing by value rather than creating a copy within the function. For instance:
void foo( widget const& w )
{
widget temp( w );
// do something with temp
}
Instead use
void foo( widget w ) // copy is made here
{
// operate on w itself
}
Doing this also has the benefit of allowing the compiler to move widget
if possible, which is generally more efficient than creating copies.
You're wrong in that you should pass by pointer. If you want to pass by reference, well... simply pass by reference:
void foo(int& x)
{
x = 3;
}
int main()
{
int a = 0;
foo(a);
assert( a == 3 );
}
Also, note that passing by value guarantees that the your variable can't be changed inside the called context. Although so would passing by const
reference...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With