0

class ListNode;

class LinkedList {

private:

    ListNode* start;

    class ListNode {
    private:
        int data;
        ListNode* next;

    public:
        ListNode() : data(-1), next(NULL) {}
        ListNode(int data, ListNode* next=NULL) : data(data), next(next) {}

    };


public:
    LinkedList() : start(NULL) {}
    LinkedList(int data) : start(new ListNode(data)) {}
};

there is a error in LinkedList(int data) : start(new ListNode(data)) {}. It says "you cannot innitialize LinkedList* value using LinkedList::ListNode construction". Whats is the exact problem means and solutions???

  • Better: [c++ - How do I forward declare an inner class? - Stack Overflow](https://stackoverflow.com/questions/1021793/how-do-i-forward-declare-an-inner-class) – user202729 Feb 06 '21 at 08:41
  • Simplest fix would be to move `ListNode* start;` after `class ListNode { ... };` (and delete the forward declaration `class ListNode;` which is simply wrong). – john Feb 06 '21 at 08:42

2 Answers2

2

The forward declaration of class ListNode; is not the same thing as class LinkedList::ListNode defined later.

When the compiler finds ListNode* start;, LinkedList::ListNode is unknown, so the compiler uses the ListNode forward declaration. By the time the compiler gets to start(new ListNode(data)), LinkedList::ListNode is known and has a closer scope so it is used instead of ListNode.

Result: start, a ListNode * is pointed at a LinkedList::ListNode. The types clash and the compiler rejects the code.

The simplest solution is to remove the forward declaration of ListNode, since it's likely just an attempt a to fix an earlier undeclared identifier error and will never be defined, and move ListNode* start; to after the definition of LinkedList::ListNode so that there is no ambiguity.

user4581301
  • 33,082
  • 7
  • 33
  • 54
0

You cannot forward declare an inner class outside the containing class. So, try declaring it first, and then declaring a pointer to it:

class LinkedList {

private:
    class ListNode {
    private:
        int data;
        ListNode* next;

    public:
        ListNode() : data(-1), next(NULL) {}
        ListNode(int data, ListNode* next=NULL) : data(data), next(next) {}

    };

    ListNode* start;

public:
    LinkedList() : start(NULL) {}
    LinkedList(int data) : start(new ListNode(data)) {}
};
Silidrone
  • 1,471
  • 4
  • 20
  • 35