Is passing pointer argument, pass by value in C++? Since i see that any change to the pointer as such is not reflected outside the method. The changes i do by dereferencing the pointer is reflected though.
In that case, is it acceptable/standard procedure to use pointer to pointer as argument to a function to modify the pointer value as such within a function?
Yes it is, as it is in C.
In which case? What do you want? You can use real references with the
&
modifier.Yes to both.
Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to the old object. But you can change the value of the object pointed to.
If you want to reflect changes made to the pointer to the external pointer (make it point to something else), you need two levels of indirection (pointer to pointer). When calling functions it's done by putting a
&
before the name of the pointer. It is the standard C way of doing things.When using C++, using references is preferred to pointer (henceforth also to pointer to pointer).
For the why references should be preferred to pointers, there is several reasons:
Drawbacks of references are mostly:
In the specific case of pointer to pointer, the difference is mostly simplicity, but using reference it may also be easy to remove both levels of pointers and pass only one reference instead of a pointer to pointer.
Either a pointer to a pointer, or a reference to a pointer, is what you would use if you wanted to potentially change the pointer itself. To your original question, technically, yes, all parameters are passed by value.
I understand the confusion here. The concepts of "pass by value" and "pass by reference" are not so clear even if they seem to be so. Bear in mind that the computer does not know these concepts and does not behave according to it. The computer does not know about the types. Hence it does not make a distinction of pointers and values. Let me try to explain by and example:
The operation is same for the machine in both functions: It gets the argument and changes it. Note that, in second function it does not modifiy *x, it modifies x.
Now if we call these functions,
I prefer to say that, basically, every function call is "call by value". But in the case of a pointer type, we have a way to change the content of another address in memory.
If we had written
func2
asThen, this would be a real case of "call by reference".