For a very long time now I’ve been looking for good explanations of pointers, and how the varying kinds differ.I’ve finally found a book that does a good job of explaining what they are and how they differ. The book is by Bjarne Stroustrup (the creator of C++) it’s called Programming: Principles and Practice Using C++. The book is supposed to teach you how to program (become a good programmer) using C++ not teach the C++ language. The question that Stroustrup poses is How do we choose between using a reference argument and using a pointer argument? his answer to the question is quite in depth, however I’ll reiterate his summary here in the hopes that it’s useful for someone.
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.