Reliable Software Logo
 Home  >  C++ Resources  > C++ In Action Book > Language: Pointers > Pointers vs. References

C++ In Action

Pointers vs. References

A pointer variable is declared with an asterisk between the type name and the variable name (the asterisk binds with the variable name). For instance,

int *pValue;
declares pValue to be a pointer to an integer. The pointer can be initialized with (or assigned to, using the assignment operator = ) an address of some other variable. The address of operator is denoted by the ampersand (there is no conflict between this ampersand and the reference ampersand--they appear in different contexts). For instance,
int TheValue = 10;
pValue = &TheValue;
assigns the address of the variable TheValue to the pointer pValue.

Figure 1. The pointer pValue stores the address of—points to—the variable TheValue.

If we want to access the value to which the pointer points, we use the dereference operator, the asterisk (again, its double meaning doesn’t lead to confusion). For instance,

int i = *pValue;
assigns the value that pValue points to, to the integer i. In our example i will change its value to 10. Conversely,
*pValue = 20;
will change the value that pValue points to, that is, the value of TheValue. (The value of TheValue will now be 20). As you can see, this is a little bit more complicated than the use of references. By the way, the same example with references would look like this:
int TheValue = 10;
int& aliasValue = TheValue; // aliasValue refers to TheValue
int i = aliasValue; // access TheValue through an alias
aliasValue = 20;  // change TheValue through an alias

References definitely win the simplicity competition.

Here’s another silly example that shows how one could, but shouldn’t, use pointers. The only new piece of syntax here is the member access operator denoted by an arrow (actually a combination of a minus sign with a greater than sign) ->. It combines dereferencing a pointer and accessing a member (calling a member function).

IStack TheStack;
IStack* pStack = &TheStack;
pStack->Push (7);  // push 7 on TheStack using a pointer
// equivalent to (*pStack).Push (7)

The same can be done using a reference:

IStack TheStack;
IStack& aliasStack = TheStack;
aliasStack.Push (7);  // push 7 on TheStack using an alias

Once more, references rule.

NextNext: Pointers and Arrays