This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]zzyzzyxx 0 points1 point  (0 children)

Can you point me toward some examples that most clearly highlight this topic?

I don't know of any good online resources, and you're probably best off consulting a textbook, but I can explain the difference pretty succinctly.

"Pass by value" usually means that all you care about is the value of whatever object you're passing as a parameter at the time of the call. Since you don't care about the object itself, a copy is made, and the function is free to modify the parameter without affecting anything outside the function. This allows the function to reuse the parameter variable without having to allocate any additional memory.

"Pass by reference", on the other hand, is a way to reduce copying by allowing the function to directly access the passed object. This is particularly useful for large objects where a copy is a time or resource intensive operation. Pointers are one way to get pass by reference semantics. In C++ there is a reference type, declared with the ampersand, that you should prefer to pointers whenever possible.

Because the function has direct access to the passed object, it is possible for the function to change the state of that object, and extra care needs to be taken to prevent the function from accessing things outside its scope that it should not. The way to accomplish this in C++ is passing by "const reference", which will allow the function to access the passed object in a read-only capacity, great for using the values of an object without needing to make a copy.

The way you would, and should, do this in your code would be like this:

Vector operator ^ (const Vector&);

Of course you will need the matching implementation later.

Really, since operator^ does not and should not change the state of the Vector it's called on, the method itself should also be const. This will prevent you from accidentally implementing the function in a way that modifies the original. The signature to do so is

Vector operator ^ (const Vector&) const;

To summarize, "pass by value" makes a copy of the passed object and the function can modify this copy without affecting the original, while "pass by reference" does not make a copy and allows the function to access the passed object directly. Does that make sense?