-3

C++:

The "pass by reference" is used if we want to change the actual variable's value, for example.

Then what is the use of "pass by const reference"? It says that it doesn't allow us to change the value of variable.

OK. Then why not use "pass by value" in the first place? :/ "Pass By Value" will also not change the value of variable. It will change the value of temporary copy.

So why use CONST Reference? o_O? I hope you are getting me.

Please help me clear my doubt.

Vipulcoolrule
  • 31
  • 1
  • 7
  • if you pass by value, you will have to invoke copy constructor. For things like int, it is really trivial, but things like strings with thousands of bytes are pretty heavy to copy, whereas if you pass in reference, you technically only pass in pointer to that memory with nicer syntax – Creris Oct 18 '14 at 14:33

1 Answers1

4

I assume you mean why do

int foo(int const& bar)

instead of

int foo (int bar)

If that is your question, passing by reference is used so that a copy doesn't need to be made. In the above example, it is trivial because the argument is an int. But if it was a large vector or map, you certainly wouldn't want to pass by value, because it would make a copy.

So if you just want to pass by reference to avoid a copy, but do not want the variable to be mutable, you would make it a const reference.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • "you certainly wouldn't want to pass by value, because it would make a copy." But sometimes you need a copy. – juanchopanza Oct 18 '14 at 14:35
  • Hi. Thanks a lot for responding so quick. I have a further question. EDIT: I guess I got it. I am too confused today. I read other similar questions too before making this thread. – Vipulcoolrule Oct 18 '14 at 14:45