[SOLVED] Where should I prefer pass-by-reference or pass-by-value?


In what circumstances should I prefer pass-by-reference? Pass-by-value?


There are four main cases where you should use pass-by-reference over pass-by-value:

  1. If you are calling a function that needs to modify its arguments, use pass-by-reference or pass-by-pointer. Otherwise, you’ll get a copy of the argument.
  2. If you’re calling a function that needs to take a large object as a parameter, pass it by const reference to avoid making an unnecessary copy of that object and taking a large efficiency hit.
  3. If you’re writing a copy or move constructor which by definition must take a reference, use pass by reference.
  4. If you’re writing a function that wants to operate on a polymorphic class, use pass by reference or pass by pointer to avoid slicing.

Answered By – templatetypedef

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *