|
|
|
|
|
|
|
Pointers provide a powerful way to access data by indirection. Every variable has an address, which can be obtained using the address of operator (&). The address can be stored in a pointer. |
|
|
|
|
|
|
|
|
Pointers are declared by writing the type of object that they point to, followed by the indirection operator (*) and the name of the pointer. Pointers should be initialized to point to an object or to NULL (0). |
|
|
|
|
|
|
|
|
You access the value at the address stored in a pointer by using the indirection operator (*). You can declare const pointers, which can't be reassigned to point to other objects, and pointers to const objects, which can't be used to change the objects to which they point. |
|
|
|
|
|
|
|
|
To create new objects on the free store, you use the new keyword and assign the address that is returned to a pointer. You free that memory by calling the delete keyword on the pointer. delete frees the memory, but it doesn't destroy the pointer. Therefore, you must reassign the pointer after its memory has been freed. |
|
|
|
|
|
|
|
|
Q Why are pointers so important? |
|
|
|
|
|
|
|
|
A Today you saw how pointers are used to hold the address of objects on the free store and how they are used to pass arguments by reference. In addition, in Hour 13, Advanced Functions, you'll see how pointers are used in class polymorphism. |
|
|
|
|
|
|
|
|
Q Why should I bother to declare anything on the free store? |
|
|
|
|
|
|
|
|
A Objects on the free store persist after the return of a function. Additionally, the capability to store objects on the free store enables you to decide at runtime how many objects you need, instead of having to declare this in advance. This is explored in greater depth in Hour 10. |
|
|
|
|
|