C++: Reasons for passing objects by value

c++, java, oop

Solution

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.

Problem

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?

Original source

Related problems