2

Can someone please give some examples where pass by reference is preferred over pass by pointer.

Basically both offer the same functionality but I want to know where pass by reference becomes mandatory.

Also, please suggest how to decide to use either of the two.

Please suggest with some basic examples.

Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54

4 Answers4

3

Copy constructor and Assignment operator.

struct A {
  ...
  A(const A& copy);
  A& operator = (const A& copy);
};

These are mandatory situations. Apart from these there can be other situations also (e.g. overloading other operators like +, <, > and so on).

Also, please suggest how to decide to use either of the two.

I prefer references (more C++ style) at most of the places and if a reference can't be used, I tend to use pointers (more C style).
Reference are somewhat analogical representation of a const pointer; i.e. A& is similar as A* const. Thus they provide some in-built safety against overwriting the location accidently.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • Actually Pass by reference is not mandatory for the assignment-operator (from the standard it seems return-by-reference isn't either). One could simply pass by value which might be advantageous for copy eliasion when using a copy-and-swap idiom. – Grizzly Apr 10 '12 at 12:07
1

My simple rule of thumb would be always to prefer pass by reference where it was possible. If you need the ability to pass a null value, then you have to use pass by pointer. Otherwise use pass by reference.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

When overloading operators it is mandatory to pass references. For example :

class A {
    A& operator=(const A &other);
}
giorashc
  • 13,691
  • 3
  • 35
  • 71
1

Copy constructors must take their argument by reference.

Operator overloads must take their arguments by value or reference, not by pointer.

For normal functions, the choice is yours; although you must use a pointer if you want to accept null arguments or dynamic arrays.

Some people prefer to use references whenever possible; there is no need to check whether it's null, and no scope for confusion about whether it refers to a single object or an array, or whether the function might delete the object. Others prefer to use pointers, as it gives a visible indication at the call site that the function might change the object.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644