Creating the Project

Create a new folder under C:\Beginning_C++ called Chapter_04. Start Visual C++ and create a C++ source file and save it to the folder you just created, as tasks.cpp. Add a simple main function without parameters, and provide support for input and output using C++ streams:

    #include <iostream> 
#include <string>
using namespace std;

int main()
{
}

Above the main function, add a definition for the structure that represents a task in the list:

    using namespace std;  
struct task {
task* pNext;

string description;
};

This has two members. The guts of the object is the description item. In our example, executing a task will involve printing the description item to the console. In an actual project, you'll most likely have many data items associated with the task, and you may even have member functions to execute the task, but we have not yet covered member functions; that's a topic for Chapter 4, Classes.

The plumbing of the linked list is the other member, pNext. Note that the task structure has not been completely defined at the point that the pNext member is declared. This is not a problem because pNext is a pointer. You cannot have a data member of an undefined, or a partially defined type, because the compiler will not know how much memory to allocate for it. You can have a pointer member to a partially defined type because a pointer member is the same size irrespective of what it points to.

If we know the first link in a list, then we can access the whole list and, in our example, this will be a global variable. When constructing the list, the construction functions need to know the end of the list so that they can attach a new link to the list. Again, for convenience, we will make this a global variable. Add the following pointers after the definition of the task structure:

    task* pHead = nullptr;
task* pCurrent = nullptr;
int main()
{
}

As it stands, the code does nothing, but it is a good opportunity to compile the file to test that there are no typos:

cl /EHsc tasks.cpp