c++linked-listoperator-overloadingostreammember-access

Overloading ostream << operator for a class with private key member


I am trying to overload the ostream << operator for class List

class Node
{
public:
    int data;
    Node *next;
};
class List
{
private:
    Node *head;
public:
    List() : head(NULL) {}
    void insert(int d, int index){ ... }
 ...}

To my humble knowledge (overload ostream functions) must be written outside the class. So, I have done this:

ostream &operator<<(ostream &out, List L)
{
    Node *currNode = L.head;
    while (currNode != NULL)
    {
        out << currNode->data << " ";
        currNode = currNode->next;
    }
    return out;
}

But of course, this doesn't work because the member Node head is private. What are the methods that can be done in this case other than turning Node *head to public?


Solution

  • You can solve this by adding a friend declaration for the overloaded operator<< inside class' definition as shown below:

    class List
    {
       //add friend declaration
       friend std::ostream& operator<<(std::ostream &out, List L);
       
       //other member here
    };