Other examples of "change by pointer": think of passing variables to functions. If you do so "by value", the function works with a temporary copy of the variable and any change made is not reflected in the original variable. If you pass a pointer to a variable, you CAN change it inside a function.
Secondly: efficiency. Imagine having a group of large objects, and you need to find one with the highest value for a certain criterium. Doing it "by value":
1 2 3 4
|
Object best;
for (all n objects) {
if (objA > best) best = objA; // Copies entire object
}
|
Which in the worst case would require n full copies of the entire Object. Instead, you can do:
1 2 3 4
|
Object* best;
for (all n objects) {
if (objA > *best) best = &objA; // Copies address
}
|
Instead of copying an object (of any size), you copy an address of 4bytes (?). 4*n instead of 4*sizeof(Object) is a big change.
Another important reason for pointers is data structures. A linked list is the easiest example: if you don't know how large a list is (thus can't simply assign an array of N items), or the sequence can change often, you can organize data by pointers.
1 2 3 4
|
class ListItem {
// Satellite data
ListItem *next, *prev;
}
|
Rather than changing the sequence by swapping (= 3 copies!) Objects in an array, you adjust the sequence by changing the next and prev pointers.