views:

392

answers:

3

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

+3  A: 

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

efotinis
+2  A: 

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.

Dror Helper
There's also boost::optional, which allows passing an invalid value, without having to use pointers or a special value denoting Empty.
efotinis
+2  A: 

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

Tyler