Linked List Problem

I'm having a small problem creating custom linked list. The List class contains an Iterator object and Iterator class contains List object. What do I declare first? It seems no matter what I am stuck...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Node {
public:
    Node(string s);
private:
    string data;
    Node* previous;
    Node* next;
    friend class List;
    friend class Iterator;
};

class List {
public:
    List();
    void push_back(string data);
    void insert(Iterator pos, string s); // PROBLEM
    Iterator erase(Iterator pos); // PROBLEM
    Iterator begin(); // PROBLEM
    Iterator end(); // PROBLEM
private:
    Node* first;
    Node* last;
    friend class List;
    friend class Iterator;
};

class Iterator {
public:
    Iterator();
    string get() const;
    void next();
    void previous();
    bool equals(Iterator b) const;
private:
    Node* position;
    const List& container; // PROBLEM
};
Last edited on
Why don't you put Node and Iterator inside the List class since they belong to the list. Using them outside the list makes no sense. Of course the Iterator class must be public.
Line 23: There is no need to declare List as a friend of itself.
Line 36: Are you sure you want the list to be const here?

The way you handle this is to use a forward declaration to tell the compiler that class List exists. This lets you declare class Iterator. Once you have declared class Iterator, you can declare class list:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Node {
public:
    Node(string s);
private:
    string data;
    Node* previous;
    Node* next;
    friend class List;
    friend class Iterator;
};

class List;			// forward declaration

class Iterator {
public:
    Iterator();
    string get() const;
    void next();
    void previous();
    bool equals(Iterator b) const;
private:
    Node* position;
    const List& container;
};

class List {
public:
    List();
    void push_back(string data);
    void insert(Iterator pos, string s);
    Iterator erase(Iterator pos);
    Iterator begin();
    Iterator end();
private:
    Node* first;
    Node* last;
    friend class Iterator;
};

Those kind of errors occur a lot when programming with c++ and it is recommended detecting them as quick as possible in order to protect you code from errors that can harm you later. If it's getting too hard you there are programs that help detecting errors, such as checkmarx or others.
Good luck with it!
Ben.
Topic archived. No new replies allowed.