hecticd
hecticd

Reputation: 27

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!

Upvotes: 1

Views: 2618

Answers (2)

gsamaras
gsamaras

Reputation: 73366

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.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

It is the person who designed this list has to provide an interface that you could access data stored in the list.

Now you can only add data to the list and output them all.

Usually such containers provide iterators that allow to traverse the list. The person should write such an interface. Otherwise there is no any usefulness of the list.

Upvotes: 1

Related Questions