I have read a number of stackoverflow answers about this and I am not quite satisfied from the responses so I wanted to gather them here.
When calling a function using non-primitive and complex objects for parameters it is generally advised to pass them by reference UNLESS there is a possibility of the parameter being NULL. This is mostly due to the fact that references are guaranteed to have a value so you don't have to check if a parameter reference is NULL.
When the return value of a function is a non-primitive and complex object you should generally return a pointer because it is easy to confuse a function that returns a reference with one that returns a value as they appear identical when called.
As an example take this class
struct Rectangle
{
int x, y;
int width, height;
Rectangle(int x_, int y_, int width_, int height_)
: x(x_)
, y(y_)
, width(width_)
, height(height_)
{
}
};
class Image
{
public:
Image()
: dimensions(0, 0, 0, 0)
{}
~Image();
void SetDimensions (const Rectangle& newDimensions) // Pass by reference is recommended practice
{
dimensions = newDimensions;
}
Rectangle GetDimensions() // Returning by value is usually the best practice in this case
{
return dimensions;
}
private:
Rectangle dimensions;
};
Are these the best practices for references vs pointers in function parameters and return types? If not, please explain why not.
EDIT 1: Changed GetDimensions() to return value because it is believed efficient