A challenge for beginners in C++s passing of parameters is that the calltype
(by-reference vs. by-value) and the type
of a parameter are easy to mix up.
A call to somefunc(SomeType* head, int value)
transfers both parameters by-value
. This means, the value is copied and the function uses the only the copy, not the original value. The parameters are named head
and value
and the types are SomeType*
and int
.
A call to somefunc(SomeType* &head, int &value)
transfers both parameters by-reference
. The value is not copied, instead a reference to the original values is created and this reference is used in the function. Changes made to either head
or value
are made via this reference to the original values. But the types of the parameters are still SomeType*
and int
.
Your example uses somefunc(SomeType* &head, int value)
. This means that head
is passed by-reference
and the original value can be changed in the function, whereas value
is passed by-value
. It's a mix of the two samples above.
It helps if you try to separate the type from the call-type
and the name.
|----------------------|----------------------|
|SomeType* &head | int value |
|----------------------|----------------------|
|^^type^^ ^by-ref^ | ^type^ ^by-value^ |
|----------------------|----------------------|
This becomes clear when you use a typedef/using declaration like this:
using SomeTypePtr = SomeType*;
someFunc(SomeTypePtr &head, int value)
Note: Technically speaking there is no such thing as a "by-reference calltype". A function will always use parameters "by-value" and the actual type of head
is SomeType*&
. It's just that the compiler creates a reference and passes it by-value. But what I described above is easier to understand.