MrPilot
MrPilot

Reputation: 173

overloading post/pre increment operators

I'm having an issue overloading the post/pre ++ operator. So I have my main class Nodelist and from this class I have a function that prints. The print function uses the Iterator class to access the ++ operator function. Everything works fine until it reaches the temp++; which causes an infinite loop; I'm using this for a linked list and while I know that nodePntr->next allows me to move to the next node I'm not sure why this does not work?

Node

struct node {
    int info;
    node* next;
};

Nodelist

class NodeList {
public:
    void Print();
private:
    node* header;
};

void Nodelist::Print()
{
    Iterator temp;

    temp = header;
    while (!temp.isNull()) {
        cout << *temp << " ";
        temp++;
    }
}

Iterator

class Iterator {
public:
    friend class Nodelist;
    Iterator();
    Iterator(node *);
    bool isNull();
    node operator++();
    node operator++(int);
private:
    node* nodePntr;
};

node Iterator::operator++()
{
    node *temp = nodePntr->next;
    return *temp;
}

node Iterator::operator++(int)
{
    node *temp = nodePntr;
    ++temp;
    return *temp;
}

Upvotes: 0

Views: 600

Answers (1)

bstamour
bstamour

Reputation: 7766

Your increment functions need to return values of type Iterator, not node, and should update the internal node stored by the iterator. Your loop never actually modifies the temp object in your Print function, hence the infinite loop.

For example, your pre-increment function might look something like this

Iterator& Iterator::operator ++ ()
{
    // Update the node inside the iterator.
    nodePntr = nodePntr->next;
    // Return a reference to the updated iterator.
    return *this;
}

and then your post-increment can be written in terms of your pre-increment

Iterator Iterator::operator ++ (int)
{
    // Make a copy. A working copy constructor is left as an exercise to the reader.
    Iterator temp(*this);
    // Call the pre-increment (code reuse);
    ++(*this); 
    return temp;
}

Upvotes: 5

Related Questions