References and Pointers: Similarities and Differences

You can also view references as pointers that you can use without the usual dereferencing notation. In the first example in this chapter, the reference otherint can be replaced with a constant pointer, as follows:

int actualint = 123;

int *const intptr = &actualint; // Constant pointer

// points to actualint

A declaration like this makes *intptr another way of referring to actualint. Consider the similarities between this and a reference declaration. Any assignments you make to *intptr affect actualint, and vice versa. As described earlier, a reference also has this property, but without requiring the *, or indirection operator. And because intptr is a constant pointer, you cannot make it point to another integer once it's been initialized to actualint. Again, the same is true for a reference.

However, references cannot be manipulated like pointers. With a pointer, you can distinguish between the pointer itself and the variable it points to by using the * operator. For example, intptr describes the pointer, while *intptr describes the integer being pointed to. Since you don't use a * with a reference, you can manipulate only the variable being referred to, not the reference itself.

As a result, there are a number of things that you cannot do to references themselves:

Point to them

Take the address of one

Compare them

Assign to them

Do arithmetic with them

Modify them

If you try to perform any of these operations on a reference, you will instead be acting on the variable that the reference is associated with. For example, if you increment a reference, you actually increment what it refers to. If you take the address of a reference, you actually take the address of what it refers to.

Recall that with pointers, you can use the const keyword to declare constant pointers and pointers to constants. Similarly, you can declare a reference to a constant. For example:

int actualint = 123;

const int &otherint = actualint; // Reference to constant int

This declaration makes otherint a read-only alias for actualint. You cannot make any modifications to otherint, only to actualint. The similarity to pointers does not go any further, however, because you cannot declare a constant reference:

int &const otherint = actualint; // Error

This declaration is meaningless because all references are constant by definition.

As mentioned earlier, the first sections of this chapter are intended to demonstrate the properties of references, but not their purpose. The previous examples notwithstanding, references should not be used merely to provide another name for a variable. The most common use of references is as function parameters.