C++ – Are there benefits of passing by pointer over passing by reference in C++

cparameter-passingpass-by-referencepointers

What are the benefits of passing by pointer over passing by reference in C++?

Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?

Example:

func(SPRITE *x);

with a call of

func(&mySprite);

vs.

func(SPRITE &x);

with a call of

func(mySprite);

Best Answer

Passing by pointer

  • Caller has to take the address -> not transparent
  • A 0 value can be provided to mean nothing. This can be used to provide optional arguments.

Pass by reference

  • Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types is not possible (pointers are builtin types). So you can't do string s = &str1 + &str2; using pointers.
  • No 0 values possible -> Called function doesn't have to check for them
  • Reference to const also accepts temporaries: void f(const T& t); ... f(T(a, b, c));, pointers cannot be used like that since you cannot take the address of a temporary.
  • Last but not least, references are easier to use -> less chance for bugs.