Pass by Reference versus Pass by Pointer in Function

Hi expert,

In all my code, I have used only pass
by reference in function.
Be it reference of Map, Int, or Vector.

My question are.
1. Is there any case where you ONLY can pass by pointer?
2. If we have two choices, pointer or reference,
how do we know which one is right for us?

It may be useful to think of using a pointer as a way of using a reference to something. The difference is that a pointer can also point to nothing by pointing to null, where as a reference is always associated with an object.

A side effect of this is that the pointer syntax can use null to indicate an error and reference syntax cannot. dynamic_cast is a good example, when using references, it can only indicate failure by throwing an exception. All of this refers to passing information out of course.

Passing information in is a different matter and are usually interchangeable.
If you do not want the function to modify the callee's actual parameters, pass by value for "simple" types such as PODs or by const reference for types that are expensive to copy. If you do want the function to modify the callee's actual parameters, pass by non-const reference.

Generally, as kbw said, when passing parameters to functions, the difference between references and pointers is that pointers can be null whereas references cannot. Pointers are preferred if null is a valid parameter value or if there is no alternative. Otherwise use const or non-const references.
Passing pointers is also useful if you want to make functions that can take pointers to a base class as well as the derived classes.
You can do that with references too.
Topic archived. No new replies allowed.