Home > Mobile >  member "Node::next" (of a friend class) is inaccessible
member "Node::next" (of a friend class) is inaccessible

Time:01-19

I am building my own LinkedList, because I need a special Node that holds more data. I specify that my Node class is a friend of the LinkedList class, but it doesn't seem to allow me to access the private variables in the Node class from the LinkedList class.

Node.h

class Node {
    private:
        Node* next;
    ...
};

LinkedList.h

#include "Node.h"

class LinkedList {
    friend class Node;
    ...
};

LinkedList.cpp

...
void LinkedList::insertFirst(Node* n) {
    Node* temp = this->root;
    this->root = n;
    this->root->next = temp; // 1
}
...

1 This is where I get the error. It says that the this->root->next is inaccessible, but I have it as a friend class to my LinkedList and so private variables should be accessible to it.

There are quite a few questions here on Stack Overflow that talk about something similar to my question, but none of them seem to be what I need.

  • One answer was saying to switch from private to protected, but that didn't work, it just changed the error to say it can't access the protected member.
  • Another answer was saying that they had a misspelling in there friend declaration. I checked mine, and it is spelled correctly.
  • Another was saying to make sure that the classes are declared in the correct order, but since I have them in different files, and #include the file where I create the class that is declared as a friend.

There were quite a few more that I looked at, but all were similar to the above mentioned and didn't help me solve my problem.

What am I missing/not understanding? Nothing I've tried has worked, and I would really appreciate any help.

CodePudding user response:

A friend declaration grants access of the specified class to the private members of the declarating class. So, you are granting Node access to LinkedList's private members, not the other way around like you want. So, you need to move the friend statement into Node instead:

class Node {
    friend class LinkedList;
    ...
};
  •  Tags:  
  • Related