Comparing Pointers and References
While both references and pointers are used to indirectly access another value, there are two important differences between references and pointers. The first is that a reference always refers to an object: It is an error to define a reference without initializing it. The behavior of assignment is the second important difference: Assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object.
Consider these two program fragments. In the first, we assign one pointer to another:
int ival = 1024, ival2 = 2048; int *pi = &ival, *pi2 = &ival2; pi = pi2; // pi now points to ival2
After the assignment, ival, the object addressed by pi remains unchanged. The assignment changes the value of pi, making it point to a different object. Now consider a similar program that assigns two references:
int &ri = ival, &ri2 = ival2; ri = ri2; // assigns ival2 to ival
This assignment changes ival, the value referenced by ri, and not the reference itself. After the assignment, the two references still refer to their original objects, and the value of those objects is now the same as well.
Pointers to Pointers
Pointers are themselves objects in memory. They, therefore, have addresses that we can store in a pointer:
int ival = 1024; int *pi = &ival; // pi points to an int int **ppi = π // ppi points to a pointer to int
which yields a pointer to a pointer. We designate a pointer to a pointer by using **. We might represent these objects as
As usual, dereferencing ppi yields the object to which ppi points. In this case, that object is a pointer to an int:
int *pi2 = *ppi; // ppi points to a pointer
To actually access ival, we need to dereference ppi twice:
cout << "The value of ival/n" << "direct value: " << ival << "/n" << "indirect value: " << *pi << "/n" << "doubly indirect value: " << **ppi << endl;
This program prints the value of ival tHRee different ways. First, by direct reference to the variable. Then, through the pointer to int in pi, and finally, by dereferencing ppi twice to get to the underlying value in ival.