I've been programming C, mainly in an embedded environment, for years now and have a perfectly good mental model of pointers - I don't have to explicitly think about how to use them, am 100% comfortable with pointer arithmetic, arrays of pointers, pointers-to-pointers etc.
I've written very little C++ and really don't have a good way of thinking about references. I've been advised in the past to "think of them as pointers that can't be NULL" but this question shows that that is far from the full story.
So for more experienced C++ programmers - how do you think of references? Do you think of them as a special sort of pointer, or as their own thing entirely? What's a good way for a C programmer to get their head round the concept?
No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
A reference is an alias or an alternative name for an object or function. All operations applied to an object reference act on the object to which the reference refers. The address of a reference is the address of the aliased object or function.
Creating References in C++int i = 17; We can declare reference variables for i as follows. C++ supports passing references as function parameter more safely than parameters. You can return reference from a C++ function like any other data type.
I've get used to think about references as an alias for main object.
EDIT(Due to request in comments):
I used to think about reference as kind of aliasing is because it behaves in the exact same way as the original variable without any need to make an extra manipulation in order to affect the variable referenced.
For me, when I see a pointer in code (as a local variable in a function or a member on a class), I have to think about
I don't have to think about any of that stuff if it's a reference, it's somebody else's problem (i.e. think of a reference as an SEP Field for a pointer)
P.S. Yes, it's probably still my problem, just not right now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With