So, the real answer is: "The choice depends on the nature of the the function":Ok, that alone seems a little confusing. I'm just going to use function declarations to denote the differences in code.
- For tiny objects prefer pass-by-value.
- For functions where "no object" (represented by a 0) is a valid argument use a pointer parameter (and remember to test for 0).
- Otherwise, use a reference parameter.
According to him, pass by value is the least error prone, but it copies memory and is therefore more expensive. To do this you'd declare a function like
int func_name(int x);."No object" in my quote is another term for "Null pointer" which he defined previous to this but wasn't in my quote. If no argument to the function is valid you'd use that. It's declared like
int func_name(int* x);The last option is to use a reference pointer. these are declared as
int func_name(int& x).I still have some trouble with the what/why/when to use pointers, but I'll probably just go back through this a few times. Stroustrup's explanation is still the best I've seen. I'd suggest his book to any novice programmer. I'm not sure if it's the best for someone who's never seen any code as it goes quite fast. It doesn't spend hardly any time at all on language constructs, which most books do. I don't think so fast that you couldn't use it as a 'first programming book' but it might be good to have a book that covers the constructs (like for loop) in depth.