The text is making this kind of confusing to me. It talks about passing by value, passing by pointer, and passing by reference. I am not quite understanding of why these different types are needed, nor do I know when a particular method should be used over another. Pass-by-value and pass-by-pointer seem to be a bit wasteful because of the copying, but pass-by-reference seems to leave a hole open...
Would any of you C++ gurus mind explaining this whole thing to me? In my Java class we only learned of one way to pass values, so this is a new thing to me.
Pass by value: a copy of the value in the variable is made in the receiving method. Any changes made to that value are only visible within that method. Once control exits that method the changes to the value of the variable are gone.
Pass by reference: a reference to a pointer is made to the variable and passed to the receiving method. Any changes made to the value of the variable are visible out side the method. References can not be reassigned.
Pass by pointer: the pointer itself is passed to the method. Any changes made to the value are visible outside the method. Pointers can be reassigned at anytime. Typically you would pass by pointer if you are working with an array.
The main differences between a reference and a pointer:
- A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
- A pointer can point to NULL while reference can never point to NULL
- You can't take the address of a reference like you can with pointers
- There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).