References are usually preferred over pointers when aliases are needed for existing objects, making them useful in parameter lists and as return values. Pointers are required when it might be necessary to change the binding to a different referent or to refer to a nonobject (a NULL pointer). Pointers often show up as local variables and member objects. An example of this can be seen in the class Array that follows. class Array { public: int& operator[] (int i); <-- 1 protected: int* data_; <-- 2 };
The only time a parameter or return value should be a pointer is when the function needs to accept or return a sentinel value. In this case the function can accept or return a pointer and use the NULL pointer as the sentinel value. |