pointer to template problem
Hi,
I wrote a template for a double linked list and i try to dynamically allocate an array where each element is a list from that template, but when i try to insert an element i get a compilation error and i don't understand the reason for getting this.
Here's the code:
template array definition:
Code:
List <gift> *buckets;
inserting the element:
Code:
gift * newGift;
...
...
buckets[pos].insertNode (*newGift);
element insertion code
Code:
template <class contain>
int List<contain>::insertNode (contain &element)
{
ListNode <contain> *temp, *newNode;
// if first element allocate first pointer.
if (!size) {
list = new ListNode <contain> (element);
lastNode = list;
return ++size;
}
//else traverse the list and insert element at the end.
temp = list;
while (temp -> getNext())
temp = temp -> getNext();
//if memory allocation error return 0
if (!(newNode = new ListNode <contain> (element))) return 0;
temp -> setNext (newNode);
lastNode = newNode;
return ++size; // else return the size of the list
}
and compiler error:
Code:
list.cpp: In member function ‘int List<contain>::insertNode(contain&) [with contain = gift]’:
santa.cpp:41: instantiated from here
list.cpp:48: error: could not convert ‘temp->ListNode<contain>::getNext [with contain = gift]()’ to ‘bool’
list.cpp:49: error: cannot convert ‘ListNode<gift>’ to ‘ListNode<gift>*’ in assignment
If any additional information is needed please let me know.
Thanks in advance.
Re: pointer to template problem
The error references the line
Code:
while (temp -> getNext())
so you should show us your definition of ListNode and ListNode::getNext().
Re: pointer to template problem
These are all the definitions for the list template, the first class is the list node and the second class is the header of the list:
Code:
template <class contain> class ListNode {
private:
contain Data;
ListNode *next;
ListNode *previous;
public:
ListNode() { next = NULL; }
ListNode (contain &);
~ListNode() {}
void setData (contain &element) { Data = element; }
contain &getData () { return Data; }
void setNext (ListNode * newNext) { next = newNext; }
ListNode &getNext () { return *next; }
};
template <class contain> class List {
private:
int size;
ListNode <contain> *list;
ListNode <contain> *lastNode;
public:
List();
~List();
int getSize () { return size; }
ListNode <contain> * getList () { return list; }
int insertNode (contain &);
int popNode ();
};
Re: pointer to template problem
getNext returns a REFERENCE, as such it must ALWAYS be a valid object. Therefore the if statement is illegal. Ift is the same as:
Code:
class A {};
A a;
if (a) {...}
Re: pointer to template problem
In your constructor of ListNode you set next to 0. Calling getNext() on such an object will result in dereferencing the null pointer, which will probably crash your program.
Simply change the class to have getNext() to return a pointer (possibly the null pointer).