Question

Could anyone explain with some examples when it is better to call functions by reference and when it is better to call by address?

Was it helpful?

Solution

Pass your arguments to function using reference whenever possible. Passing arguments by reference eliminate the chance of them being NULL. If you want it to be possible to pass NULL value to a function then use pointer.

OTHER TIPS

This has already been discussed. See Pointer vs. Reference.

One nice convention is to:

  • Pass objects by pointer whenever they may be manipulated (side-effect or as output) by the function.
  • Pass all other objects by const reference.

This makes it very clear to the caller, with minimal documentation and zero performance cost, which parameters are const or not.

You can apply this to primitive types as well, but it's debatable as to whether or not you need to use const references for non-output parameters, since they are clearly pass-by-value and cannot act as output of the function in any way (for direct types - not pointers/references - of course).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top