Imagine that we want to write a program for a library.
The library has books - for example 'Accelerated C++' by Koenig and Moo.
We decide to represent a book as a class.
The library has members; we decide to represent a member as another class.
struct member { /* member stuff */ };
Members may borrow books from the library; after the member returns a book, the same book may be issued to another member. The same member may borrow several books.
For each book, we need to keep track of the identity of the member who currently has the book.
To implement this kind of situation, we need some mechanism for indirection. For instance, if information about the members is stored in a database table with the
memberid as the key, we can have:
1 2 3 4 5 6 7 8 9 10 11
|
struct book
{
// book stuff title, copy number etc.
memberid currently_with = invalid_id ; // id of member currently having the book
// to start with, the book is not with any member: set currently_with = invalid_id ;
// the book is issued to member with id RBX129k: set currently_with = RBX129k
// RBX129k returns the book: set currently_with = invalid_id ;
// the book is later issued to member with id xismn : set currently_with = xismn
};
|
If member objects are held in memory, we can have:
1 2 3 4 5 6 7 8 9 10 11
|
struct book
{
// book stuff title, copy number etc.
member* currently_with = nullptr ; // address of member currently having the book
// to start with, the book is not with any member: set currently_with = nullptr ;
// the book is issued to member RBX129k: set currently_with = address of RBX129k
// RBX129k returns the book: set currently_with = nullptr ;
// the book is later issued to member LB : set currently_with = address of LB
};
|
LB may have borrowed five books; in all of those five books,
currently_with
would be set to the address of the same LB object.
There is no good way to model this kind of relationship between objects in memory other than by using pointers. Or indirectly using pointers (use something that uses pointers internally - eg. smart pointers or reference wrappers).
Think of pointers as an indirect way of referring to an object.
Typically, we wouldn't use pointers (dumb or smart) unless we couldn't do without them.