1
votes

I am very new to C++ templates. I am currently working on a project where I need to implement a Doubly Linked List using a template. Here is currently what I have so far:

template<class ItemType>
class SortedList
{
public:
   SortedList();
   ~SortedList();
   bool Insert (ItemType toAdd);
   bool Delete (ItemType toDelete);
   void Print();

private:
   SortedList ( const SortedList & copyFrom );
   SortedList & operator= ( const SortedList & assignFrom );

   struct Node
   {
      Node ( ItemType item, Node * p = NULL, Node * n = NULL )
      { data = item; prev = p; next = n; }
      ItemType data;
      Node * prev, * next;
   };
   Node * list;
};

template<class ItemType>
SortedList<ItemType>::SortedList()
{
   list == NULL;
}

template<class ItemType>
SortedList<ItemType>::~SortedList()
{
   Node * curr = list;
   while ( curr != NULL )
   {
      Node * tempNext = curr->next;
      delete current;
      current = tempNext;
   }
}

However, in my destructor for example, why can't I access the node elements? The code that is inside that method right now compiled, but does not throw errors. However if I try to use -> on curr, next or prev do not appear. Why do I not have access to these? I feel like I am missing something very obvious here to get started.

Also, how can I initialize list == NULL in the function head, instead of doing it outside of the class?

1
There's a typo in the constructor. It should be list = NULL; You don't use == to initialize, but to compare.mots_g

1 Answers

0
votes
  1. Don't know why it compiles, but you are using

delete current; current = tempNext;

Instead of:

delete curr;
curr = tempNext;
  1. Use inline initializer syntax:

class SortedList { public: SortedList() : list(nullptr) { }

  1. Use the same syntax to initialize Node (it's more optimal)