1

I studied that objects can be passed by referece (I mean that the parameters of the function are references). But why one prefers them over simply passing objects. My motive is to just use that object and in no sense modify it, so I do not mean the trivial advantages. So, what are the advantages of passing a reference to an object?

  • 1
    You avoid copying it. Some objects are expensive to copy; others can't be copied at all and thus can't be passed by value. – Igor Tandetnik Aug 30 '15 at 15:26
  • @IgorTandetnik is there also an advantage of memory because if the objects were not passed by reference, then the parameter objects(copies) would take more(extra) memory and also there destructors would be called once the function scope ends? –  Aug 30 '15 at 15:30
  • It's the same thing. "Making a copy" necessarily implies "allocating memory to hold the copy" and "eventually destroying the copy". – Igor Tandetnik Aug 30 '15 at 15:32

1 Answers1

2

Here are some advantages of passing by reference:

  1. No new copy of variable is made, so overhead of copying is saved. This Makes program execute faster specially when passing object of large structs or classes.
  2. Array or Object can be pass
  3. Sometimes function need to change the original value(eg. Sorting an array, swapping) and sometimes changing value inside function is useful.
  4. Can return multiple values from a function.
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42