< Previous | Contents | Next >
In this chapter, you should have learned the following concepts:
n Computer memory is organized in an ordered way, where each chunk of memory has its own unique address.
n A pointer is a variable that contains a memory address.
n In many ways, pointers act like iterators from the STL. For example, just as with iterators, you use pointers to indirectly access an object.
n To declare a pointer, you list a type, followed by an asterisk, followed by a name.
n Programmers often prefix pointer variable names with the letter “p” to remind them that the variable is indeed a pointer.
n Just like an iterator, a pointer is declared to refer to a value of a specific type. n It’s good programming practice to initialize a pointer when you declare it. n If you assign 0 to a pointer, the pointer is called a null pointer.
n To get the address of a variable, put the address of operator (&) before the variable name.
n When a pointer contains the address of an object, it’s said to point to the object.
n Unlike references, you can reassign pointers. That is, a pointer can point to different objects at different times during the life of a program.
n Just as with iterators, you dereference a pointer to access the object it points to with *, the dereference operator.
n Just as with iterators, you can use the -> operator with pointers for a more readable way to access object data members and member functions.
n A constant pointer can only point to the object it was initialized to point to. You declare a constant pointer by putting the keyword const right before the pointer name, as in int* const p = &i;.
n You can’t use a pointer to a constant to change the value to which it points. You declare a pointer to a constant by putting the keyword const before the type name, as in const int* p;.
n A constant pointer to a constant can only point to the value it was initialized to point to, and it can’t be used to change that value. You declare a constant pointer to a constant by putting the keyword const before the type name and right before the pointer name, as in const int* const p = &I;.
n You can pass pointers for efficiency or to provide direct access to an object.
250 Chapter 7 n Pointers: Tic-Tac-Toe 2.0
n If you want to pass a pointer for efficiency, you should pass a pointer to a constant or a constant pointer to a constant so the object you’re passing access to can’t be changed through the pointer.
n A dangling pointer is a pointer to an invalid memory address. Dangling pointers are often caused by deleting an object to which a pointer pointed. Dereferencing such a pointer can lead to disastrous results.
n You can return a pointer from a function, but be careful not to return a dangling pointer.