C++ References
15 Jan 2013Introduction
I’ve always thought of a reference as the half-way house between pointers and statically allocated objects. References are in-fact addresses but they are used within our code just like objects as opposed to requiring pointer syntax.
Some facts ..
How reference are defined
You declare a reference variable using the ampersand &
to modify the type declaration.
A reference must be initialised
This is pretty basic, it just means that when you declare your reference it must start out with a place to reference.
A reference cannot be changed
When we initialise a reference to point to a variable, that’s it. We can’t change what the reference points to. This caught be out to begin with, but it’s pretty easy stuff.
Makes sense. Gives references a sense of stubbornness (and sanity).
Pointer compatibility through dereferencing
I see a fair bit of banter on “how to convert pointer to reference”, etc. It’s really quite simple and it’s also subject to the same assignment laws as above.
These concepts really come into their own (I think) once you start using them within your own class structures. It’s a much more natural feel to deal with references rather than pointers and a bit easier to read as well.