seeplus wrote: |
---|
Note that head is passed by value. |
This. Function parameters in C++ have two options:
by value or
by reference. C had only by value.
The confusion is due to the parameter being a pointer.
Note that modern C++ has alternatives to the use of raw pointers, so one can do much without pointers.
Lets take simple example:
1 2 3 4 5 6 7 8 9
|
int func( int two ) {
two = 42; // does not change one
return two;
}
int main() {
int one = 7;
std::cout << func( one );
}
| |
The 'func' takes a parameter by value. The initial value of 'two' is copied from 'one' on the function call.
Changing 'two' within function does not change the caller's variable.
Lets use alias for int:
1 2 3 4 5 6 7 8 9 10 11
|
using T = int;
T func( T two ) {
two = 42; // does not change one
return two;
}
int main() {
int one = 7;
std::cout << func( one );
}
| |
Nothing did change.
Now, lets make a function that does take by reference:
1 2 3 4 5 6 7 8 9 10 11
|
using T = int;
T reffunc( T& two ) {
two = 42; // does change one
return two;
}
int main() {
int one = 7;
std::cout << reffunc( one );
}
| |
The 'two' is now a reference to 'one' and therefore the 'one' is changed by 'refrunc'.
Plan B. Pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
using T = int;
T ptrfunc( T* two ) {
*two = 5; // does change one
// two points to one
T three {};
two = &three; // two now points to three. one did not change.
*two = 42; // does change three. one did not change
return *two;
}
int main() {
T one = 7;
std::cout << ptrfunc( &one );
}
| |
Here 'two' is a pointer. Its value is an address. The value is initialized during function call. The value is a copy.
We can modify the caller's variable that the pointer points to.
However, when we change the value of the pointer, the 'two' no longer points to 'one'. It now points to 'three'.
Finally.
1 2 3 4 5 6 7 8 9 10 11 12
|
using T = int*;
void ptrfunc( T* two ) {
*two = new T;
}
int main() {
int one = 7;
T head = &one; // head points to one
ptrfunc( &head );
// head does not point to one
}
| |
On this call the 'two' points to 'head'.
The
*two = new T;
modifies the pointed to object just like
*two = 5;
did.
The only difference is that now pointed to object is a pointer (and hence 'two' is a pointer to pointer).