Search code examples
c++classlinked-listprivate-members

Accessing Linked List private variable from outside class


I am currently working on a program that will access a linked list written by another person. I'm assuming this person will have declared the head and tail variables as private, but I would like to iterate through their linked list.

Here is a possible linked list implementation

/* singly linked list node */
struct SLLNode {
    int data;
    SLLNode *next;
};

/* singly linked list implementation */
class SLinkedList {
public:
    SLinkedList();
    ~SLinkedList();

    void addToTail(int newData);
    void addToHead(int newData);

    friend std::ostream& operator<<(std::ostream&, const SLinkedList&);

private:
    SLLNode *head;
    SLLNode *tail;
};

I would like to access the pointer to the head in order to be able to iterate through the linked list.

How can I access that pointer without being able to change the nodes? Not being able to change simply for safety. Thanks in advance!


Solution

  • You can't, because it is private.

    The other person needs to provide access to you, with a public member function for example.

    As for an example, you can take a look at this question.