Here I have a simplified version of a linked-list implementation I have been working on. I would like to keep a count of component elements (nodes) as a private member, and then let the Component
constructor and destructor completely handle the variable count
.
However, I'm getting a compiler error (VS2015) disallowing access to count
by any member functions (including the constructor and destructor) that I have in Component
:
'count': undeclared identifier
Why does the friend
declaration not grant that access in this case?
class Outer {
private:
class Component;
friend class Component;
public:
Outer() : count(0) {}
unsigned int size() {
return count;
}
void methodThatCreatesComponents() {
entryPoint = new Component(nullptr);
// I don't want to have to write ++count; every time I construct
}
void methodThatDeletesComponents() {
delete entryPoint;
// I don't want to have to write --count; every time I delete
entryPoint = nullptr;
}
private:
unsigned int count;
Component* entryPoint;
class Component {
public:
Component(Component* next) {
++count;
}
~Component() {
--count;
}
private:
Component* next;
};
};