Using Pointers in Practice

A common requirement is to have a collection that can be an arbitrary size and can grow and shrink at runtime. The C++ Standard Library provides various classes to allow you to do this, as will be described in Chapter 5, Using the Standard Library Containers. The following example illustrates some of the principles of how these standard collections are implemented. In general, you should use the C++ Standard Library classes rather than implementing your own. Further, the Standard Library classes encapsulate code together in a class and since we have not covered classes yet, the following code will use functions that potentially can be called incorrectly. So, you should regard this example as just that, example code. A linked list is a common data structure. These are typically used for queues where the order of items is important. For example, a first-in-first-out queue where tasks are performed in the order that they are inserted in the queue. In this example, each task is represented as a structure that contains the task description and a pointer to the next task to be performed.

If the pointer to the next task is nullptr then this means the current task is the last task in the list:

    struct task 
{
task* pNext;
string description;
};

You can access members of a structure using the dot operator through an instance:

    task item; 
item.descrription = "do something";

In this case, the compiler will create a string object initialized with the string literal do something and assign it to the description member of the instance called item. You can also create a task on the free store using the new operator:

    task* pTask = new task; 
// use the object
delete pTask;

In this case, the members of the object have to be accessed through a pointer, and C++ provides the -> operator to give you this access:

    task* pTask = new task; 
pTask->descrription = "do something";
// use the object
delete pTask;

Here the description member is assigned to the string. Note that since task is a structure there are no access restrictions, something that is important with classes and described in Chapter 4, Classes.