The general rule is:
do not use a pointer unless you know that you can't do without one.
(When writing a program, you would know when you can't do without one.)
A pointer is one way of indirectly referring to an object; and this is quite often useful in practice. For example:
1 2 3 4 5 6 7 8
|
class some_class { /* ... */ } ;
class my_class { public: some_class* other_object ; } ;
class your_class { public: some_class* other_object ; } ;
some_class some_object ;
my_class my_object ; my_object.other_object = &some_object ;
your_class your_object ; your_object.other_object = &some_object ;
|
Both my_object and your_object can use the same some_object in a shared manner.
A pointer can point to different objects at different points in time. For instance:
1 2
|
some_class a_different_object ;
my_object.other_object = &a_different_object ;
|
A pointer can specify that there is no object at all; it may be a null pointer:
my_object.other_object = nullptr ;
As Duoas has already pointed out, pointers are useful when polymorphism is involved - that is the static type of the pointed object is not identical to the dynamic type of the object (this idea may be a little beyond you right now, but you would encounter it soon enough).
In many cases, you may not know if an object is required or how many objects are required at the time you write the code. For instance:
1 2 3 4
|
Loop:
Read input from the user.
If input is 'quit' break out of the loop
Else Create another object based on the input, and loop again.
|
In a situation of this kind, we have to create anonymous (unnamed) objects with a dynamic storage duration (eg. new some_class), which are only reachable via the pointer (that new returns).
One of the most common uses of a pointer (or something that has pointer semantics) is when we want to iterate through a sequence. For example, if we have a list of books (we do not know how many books there are at the time we write the code), and we want to print out the title and author of each of these books, our code would look something like:
1 2 3 4 5 6
|
initialize a pointer to point to the first book.
repeat:
print out the title and author of the book pointed to
make the pointer point to the next book
if the pointer is not null (there is a next book), go to repeat
else we are done.
|