Iterator in linked list

Hi,
This is the first time using an iterator. I am trying to implement one for my linked list but I am stuck on the begin function. My compilation error is "'Iterator' does not name a type;" in List.cc (begin function). I know I am probably doing something very obiuosly wrong but have been stuck for 2 hours and don't know what to do. Plz halp.

List.h:
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
#ifndef LIST_H
#define LIST_H

class Sorted_List
{
private:
    class Node
    {
    public:
        int value;
        Node* prev;
        Node* next;
    };
    Node* first;
    Node* last;
    
public:
    //constructors and functions
    
    class Iterator
    {
    public:
        Iterator(Node *n);
        Iterator begin();

    private:
        Node* it;
    };
};
#endif 


List.cc:
1
2
3
4
5
6
7
8
9
10
11
#include "List.h"
//implementations

Sorted_List::Iterator:: Iterator(Node *n) : it{n}
{
}

Iterator Sorted_List::Iterator:: begin()
{
    return Iterator(first->next);
}
 
Sorted_List::Iterator Sorted_List::Iterator::begin()
Of course, makes sense! But then I get invalid use of non-static data member 'Sorted_List::first' on line 10 of List.cc.
Right, I wasn't paying attention.

begin() must be a member of the list class, not of the iterator class. The iterator has no way to find the list's head, all it has is a pointer to a node. Not to mention, it's a bit silly to construct an iterator to a random node just to get an iterator to the head.

As for why you're getting that particular error: to access non-static members of a class you need a pointer to the instance of the class that you're going to use. Without it, just the member of the class by itself is meaningless. How would the program know which instance you mean out of the possibly hundreds or thousands?
I understand now. Thanks alot, Sensei!
Topic archived. No new replies allowed.