Consider the following sample code for a linked list type class. I wish to declare a method which returns an Iterator, which is a typedef
for a Node*
. However, Node
is a private nested class so in order to make the typdef
, i am required to let the compiler know about Node
with a forward declaration.
Naively, I thought having both defaulted to private would work; something like this:
class List
{
class Node;
typedef Node* Iterator;
public:
List() : head_(NULL), tail_(NULL) {}
Iterator begin() {return head_;}
private:
class Node
{
private:
int data_;
};
Node* head_;
Node* tail_;
};
int main()
{
List list;
List::Iterator = list.begin();
return 0;
}
which results in a compile time error at line 4:
'typedef class List::Node* List::Iterator' is private
compilation terminated due to -Wfatal-errors.
It isn't difficut to see why the forward declaration class Node;
belongs in the private section, but what about typedef Iterator Node*;
? This probably owes to my lack of understanding for the typedef
keyword, but why does it matter which access specifier is applied? I thought private
makes more sense because of the visibility of the Node
class.
Does this have something to do with typedef
s being part of the public interface? Do all typedefs have to be declared with public
visibility?
Edit: Allow me to clarify, I understand that I can stop my compiler from complaining by moving the typedef to public. What I don't understand is why this is necessary.