tags:

views:

452

answers:

3

For my programming class I have to write a linked list class. One of the functions we have to include is next(). This function would return the memory address of the next element in the list.

#include <iostream>
using namespace std;

class Set {
    private:
     int num;
     Set *nextval;
     bool empty;
    public:
     Set();
     <some return type> next();
};

<some return type> Set::next() {
    Set *current;
    current = this;
    return current->next;
}

int main() {
    Set a, *b, *c;
    for (int i=50;i>=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question

    // Test the next_element() iterator
    b = a.next();
    c = b->next();
    cout << "Third element of b = " << c->value() << endl;

    return 0;
}

As you can see, I need to set the pointer *b and *c to the memory address that holds the next element in the list. My question is what kind of return type would I use? I've tried putting Set and Set* in place of but get compiler errors. Any help is greatly appreciated.

+6  A: 

Set* is correct. You are suffering from a rather silly bug in this function:

Set* Set::next() {
    Set *current;
    current = this;
    return current->next;
}

The last line should be return current->nextval. Otherwise you are trying to return a pointer to the next function... probably not what you want, ever. :-)

luqui
+5  A: 

luqui is correct, although your next function is overly complex, there's no reason to copy the this pointer, that's just silly. Use this instead:

Set* Set::next() {
    return nextval;
}
Mel Green
A: 

Wow, thanks for catching that for me guys. I totally forget that I had switched all my next variables to nextval in order to get rid of that naming conflict.

blcArmadillo
Good thing the typechecker caught it!
luqui