Rudy
Rudy

Reputation: 7044

passing reference in C++ using const var&

I have a problem that similar to : this question

But I still don't understand what is the difference between :

void test(TestInfo&)
{

}

and

void test(const TestInfo&)
{

}

Upvotes: 2

Views: 1534

Answers (3)

zar
zar

Reputation: 12227

In addition to what @Als said, the significant of the 2nd is that even though the variable is passed by reference it functions similar to as if passing by value. This can be useful if you are passing a large object. Passing an object by value creates a new object on stack but passing by reference doesn't. When you do const TesetInfo&the new variable will not be created but it will essentially function as if it is passed by value. This will be slightly efficient approach.

Upvotes: 2

Carl
Carl

Reputation: 44438

In addition to not being able to modify the argument passed in, if TestInfo is a class for example, you'll get compile errors if you try and call non const member functions on it ( Const member functions are functions that promise not to modify the object).

Here are a couple of good reads on const:

  1. Const tutorial
  2. Const correctness

Upvotes: 0

Alok Save
Alok Save

Reputation: 206508

The first passes a reference while the second passes an const reference to the function test(),
Note that const reference basically means a reference to a const data.

In the second case you cannot modify the contents of TestInfo inside the function.
Any attempt to modify the passed TestInfo object inside the function would result in a
Undefined Behavior.

Upvotes: 7

Related Questions