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.
private
to protected
, but that didn't work, it just changed the error to say it can't access the protected member.#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.
A friend
declaration grants access of the specified class to the private members of the declaring class (ie, "that class X over there is a friend of mine, he has permission to use my private stuff").
So, by declaring Node
as a friend
inside of LinkedList
, you are granting Node
access to LinkedList
's private members, not the other way around like you want.
To let LinkedList
access Node::next
, you need to declare LinkedList
as a friend
of Node
instead:
class Node {
friend class LinkedList;
...
};