2

Possible Duplicate:
What's the difference between passing by reference vs. passing by value?

If I have a function that takes in some parameters and then does something with the parameters without needing to change their inherent value, is there any benefit from using pass by reference versus pass by value?

3
  • I understand what the difference is. My question mostly pertains to when to use one or the other, but thanks for the thread link. It was pretty informative anyways. Commented Dec 20, 2011 at 7:36
  • @ Sara : This forum will help you to understand the difference between pass-by-value and pass-by-reference stackoverflow.com/questions/410593/pass-by-reference-value-in-c Commented Dec 20, 2011 at 7:37
  • @Sara: If you understand what the difference is, then when to use one or the other depends only on what you're doing. If you need the features of one, then use that. If you need the features of the other, then use that. Commented Dec 20, 2011 at 7:50

2 Answers 2

4

Yes. Passing by value copies the argument, which might be very expensive (or not even possible). If you want to pass by reference, but not modify the object, pass by const-reference.

As an example of an object that cannot be passed by value:

class Foo { public: Foo() {} private: Foo(const Foo&); // copy-constructor is not accessible } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! When exactly is it not possible to pass a param by value but only by reference?
@Sara when it does not have an accessible copy constructor.
3

Here is the general guide:

  • Pass by reference when
    • You need to cause a side effect on the object that will be visible to the caller
    • or you cannot pass by value because of the lack of an accessible copy constructor or something and you need side effects
  • Pass by const reference when you have
    • A large object
    • and/or you cannot pass by value
    • and/or no need for side effects
  • Pass by value when
    • The object is small
    • and/or You do not need side effects
    • and/or You need a copy of the value to work with anyway

1 Comment

You should also pass by value if you are going to copy the object inside the function anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.