Call by value, reference and name [duplicate]
-
05-07-2021 - |
Question
Possible Duplicate:
Pass by Reference / Value in C++
I was wondering what the difference is between a call by value/reference/name. And why would it be beneficial to use one over another?
Solution
call by value: a copy of the parameters is passed to the function
call be reference: no extra copy is made, the caller's variable is passed directly.
Major difference is that one extra unnecessary copy is made in call by value paradigm... You should always use call be reference (or const reference) unless a callee needs to modify the variable and you don't want the changes to your caller's variable...
OTHER TIPS
Call by value creates a copy of the argument which gets passed to the function - so for a large object that could create a large overhead. It also stops you making any changes to the argument inside the function as they will be reflected in the copy only. Call by reference passes a reference to the object and so changes can be made to that object - unless of course you pass by const
reference.