Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding nested class in stack implementation using Linked List

In the stack using Linked List example impl, as below, why do we need to create Element as a nested class in the Stack class? Also, why do we need to make it protected? I am looking for the reason behind this design?

class Stack{
  public:
  Stack();
  ~Stack();
  void push(void *data);
  void *pop();
  protected:
   class Element{
   public:
     Element();
     Element *getNext() const {return next; }
     void *value() const {return data;}
   private:
     Element *next;
     void *data;
   };
   Element *head;
 };
like image 522
codey modey Avatar asked Mar 09 '26 21:03

codey modey


1 Answers

The general rule is that any item should have the most restricted visibility possible. If Element were a top level class, anyone could refer to it. If it were public, anyone could refer to Stack::Element. This is "showing your privates" -- revealing implementation details that are used only internally to the world.

As to why it's protected rather than private, that's a bit odd. The Stack class is not obviously designed to be subclassed (its destructor is not virtual, for example), so private would almost certainly be more appropriate.

like image 121
addaon Avatar answered Mar 12 '26 12:03

addaon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!