The Craft Of Coding

CPP 9-May Reminders about pointers

Posted by Pete Mon, 09 May 2016 02:40:00 GMT

As part of creating the linked list, need to use pointers

LinkedList* pList= new LinkedList();
    delete pList;

Key things to remember

  1. Whenever you use new, you must remember to use delete
  2. Simplest to use the pList->add(2)
  3. But can do it by dereferencing the pointer (*pList).add(2), but in this case need brackets since the precedence of the . is higher than that of the *
  4. Destructor only has to be virtual if you plan on subclassing
  5. Do not invoke delete on anything you did not create with new
  6. Remembering if a variable is a pointer is easier if you prefix it with the letter p

Pointers in loops

A common need when working with pointers in loops is to test that the pointer is not null, this can be done in two ways

   while (pNode != NULL) {

or you can rely on the C++ definition of 0 as false and all other values are true

   while (pNode) { 

So if the pointer holds an address, then the value is true, if it is null, then the test is false.

© Pete McBreen 2016 It was amazing, he thought, how people would argue against figures on no better basis than ‘they must be wrong’. — Terry Pratchett (Unseen Academicals )