sircodesalot
sircodesalot

Reputation: 11439

Why does dereferencing nodes break my linked-list?

So I'm trying to implement a run of the mill linked list in C++

template<class T>
class Node
{
private:
    Node *next;
    T item;

public:
    Node(T item)
        : item(item)
    {
        this->next = NULL;
    }

    Node<T> add(T item) {
         this->next = new Node(item);
         return *this->next;
    }

    bool hasNext()
    {
        return this->next == NULL;
    }

    Node<T> getNext()
    {
        return *this->next;
    }

    T value()
    {
        return this->item;
    }
};

void main()
{
    Node<int> node(3);
    node.add(3).add(4);

    cout << node.value();
    cout << node.getNext().value();
    cout << node.getNext().getNext().value();

    cin.get();
}

but I can't get it to work. In particular this section:

    node.add(3).add(4);

    cout << node.value();
    cout << node.getNext().value();
    cout << node.getNext().getNext().value();

if I change my add and getNext functions to return Node<T>* instead of Node<T>, it works fine. But why does dereferencing cause the code to break? I think the . notation makes more sense than ->, but I can't get it to work. What am I doing wrong?

Upvotes: 2

Views: 384

Answers (1)

Danny
Danny

Reputation: 2281

Right now you are making a copy of the node you added rather than returning the actual node you created. The parenthesis just add a bit of clarity for other people who have to look at your code later. The add function needs to be changed like this:

Node<T>& add(T item) {
     this->next = new Node(item);
     return *(this->next);
}

or you could return a pointer to the newly created node, but this breaks using the . rather than -> in main.

Also similar changes need to be made to next()

Upvotes: 7

Related Questions