Search code examples
c++doubly-linked-list

How to create a constructor of linked list for iterator class in c++?


When I try to run this code I get this error :

constructor for 'Linkedlist' must explicitly initialize the member 'point' which does not have a default constructor Linkedlist::Linkedlist()

class Node {
    public:
        Node* next;
        Node* prev;
        Elem elem;
        friend class Linkedlist;
        Node(): next(NULL), prev(NULL)
        {}
        Node(Elem elem) : elem(elem)
        {}
};

class Iterator {
private:
    Node* iter;
    //Iterator(Node curr);
public:
    friend class Linkedlist; 
    Iterator(Node* curr) {
        iter=curr;
    } 
};

class Linkedlist { 
private:
    Node *head;
    Node *tail;
    int N;
    Iterator point;
public:
    Iterator point;
    Linkedlist();
};

Linkedlist::Linkedlist() {
    N = 0;
    head = new Node();
    tail  = new Node();
    head->next = tail;
    tail->prev = head;
    point.iter = head;
}

I am not sure how to solve this problem, any help appreciated!


Solution

  • There are a couple of things you could do. You could declare it as a pointer

    class Linkedlist { //Missing a c on your class declaration
        private:
            Node *head;
            Node *tail;
            int N;
            //Iterator point; (You have this declared twice)
    
    
        public:
            Iterator *point;
            Linkedlist();//s
    

    In this case you'd need to call the constructor for point in the LinkedList constructor like so.

    Linkedlist::Linkedlist() {
            N = 0;
    
            head = new Node();
            tail  = new Node();
            head->next = tail;
            tail->prev = head;
            point = new Iterator(head); // Use the existing constructor
    }
    

    Alternatively, you could create a default constructor for the Iterator class.

    class Iterator {
               private:
                   Node* iter;
               public:
                   friend class Linkedlist;
                   Iterator() {
                       iter = 0;
                   }
                   Iterator(Node* curr) {
                        iter=curr;
                   } 
            };
    

    Finally, you could use this syntax that instructs the program to allocate point with a null pointer before allocating memory for LinkedList.

    Linkedlist::Linkedlist() : point(0) {
            N = 0;
    
            head = new Node();
            tail  = new Node();
            head->next = tail;
            tail->prev = head;
            point.iter=head;
    }