c++inner-classestemplate-classes

Im making a list with iterators and node classes nested in it but for some reason the iterator class is not making the list class a friend


 template <class T>
class List
{
class Node
{
public:
    Node()
    {
        next = 0;
        data = 0;
    }
    Node* next;
    T data;
};
Node* head = new Node;
Node* tail = new Node;
int size = 0;
public:
class Iterator
{
 Node* curr;
    friend class List<T>;
public:
 Iterator()
    {
        curr = nullptr;
    }
    friend void fun()
    {
        cout << "helloworld" << endl;
    }
    Iterator begin()
    {
        Iterator it(head->next);
        return it;
    }
};
};

created two more class of blocks and programs, programs contained a list of blocks. Implemented iterators for ease of use, But am not able to access its public and private members through list class.

int main()
{
List<int> l1;
List<int>::Iterator it;
it = l1.begin();
fun();//iterator befriending neither class nor function
}

Error was: class List has no member begin E0135 begin: is not a member of class list C2039 On vs22


Solution

  • In your main-function you are declaring a List<int> and an List<int>::Iterator. Where are you calling begin()? On l1, which is a List<int>.

    List<int> l1;
    List<int>::Iterator it;
    //   VV -> That's the List<int>
    it = l1.begin();
    

    Does List<int> have a definition of begin()? No. This function is defined in List<int>::Iterator.

    I think you have a misunderstanding about the meaning of friend here. It means, the friend class (List<T> in this case) is allowed to access private or protected members of the class (Iterator in this case).

    It does not make List<T>::head magically available in Iterator. It does not make Iterator::begin accessible on an instance of List<T>.


    I suggesst the following small change: move the declaration of begin from Iterator to List<T> and provide an appropriate constructor for Iterator. You can then remove any friend-declarations, as they are not needed.