< Previous | Contents | Next >
A constant pointer to a constant combines the restrictions of a constant pointer and a pointer to a constant. This means that a constant pointer to a constant can only point to the object that it was initialized to point to. In addition, it can’t be used to change the value of the object to which it points. Here’s the declaration and initialization of such a pointer:
const int* const pBONUS = &BONUS; //a constant pointer to a constant
The preceding code creates a constant pointer to a constant named pBONUS that points to the constant BONUS.
Hin t
Like a pointer to a constant, a constant pointer to a constant can point to either a non-constant or constant value.
You can’t reassign a constant pointer to a constant. The following line is not legal.
pBONUS = &MAX_LIVES; //illegal - - pBONUS can’t point to another object
You can’t use a constant pointer to a constant to change the value to which it points. This means that the following line is illegal.
*pBONUS = MAX_LIVES; //illegal - - can’t change value through pointer
In many ways, a constant pointer to a constant acts like a constant reference, which can only refer to the value it was initialized to refer to and which can’t be used to change that value.
Hin t
Although you can use a constant pointer to a constant instead of a constant reference in your programs, you should stick with constant references when possible. References have a cleaner syntax than pointers and can make your code easier to read.
234 Chapter 7 n Pointers: Tic-Tac-Toe 2.0