Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Reasons for passing objects by value

Tags:

java

c++

oop

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?

like image 382
clstaudt Avatar asked Nov 27 '22 04:11

clstaudt


2 Answers

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.

like image 96
Praetorian Avatar answered Dec 05 '22 17:12

Praetorian


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...

like image 39
Luchian Grigore Avatar answered Dec 05 '22 16:12

Luchian Grigore