Search code examples
c++linked-listdoubly-linked-list

Double linked list in Data Structures and Algorithms in c++


So i saw this code fragment in Data Structures and Algorithm in c and c++:

class DLinkedList { // doubly linked list
public:
    DLinkedList(); // constructor
    ~DLinkedList(); // destructor
    bool empty() const; // is list empty?
    const Elem& front() const; // get front element
    const Elem& back() const; // get back element
    void addFront(const Elem& e); // add to front of list
    void addBack(const Elem& e); // add to back of list
    void removeFront(); // remove from front
    void removeBack(); // remove from back
private: // local type definitions
    DNode* header; // list sentinels
    DNode* trailer;
protected: // local utilities
    void add(DNode* v, const Elem& e); // insert new node before v
    void remove(DNode* v); // remove node v
};

and my question is: why are the member functions add() and remove() protected (and when I should use the keyword protected)

edit: DNode is defined here:

typedef string Elem; // list element type
class DNode { // doubly linked list node
private:
    Elem elem; // node element value
    DNode* prev; // previous node in list
    DNode* next; // next node in list
    friend class DLinkedList; // allow DLinkedList access
};


Solution

  • you use protected when you don't want the API to view certain methods but do want to access the method from the class and its subclasses(outside or within package) and classes from the same package

    the reason add() and remove() are protected is to provide data abstraction and to prevent unauthorized personnel from using these functions