I have a class Node. This class can add or remove other nodes relative to itself. Node is used by a List class. To prevent the nodes being modified directly (externally, IE not by the appropriate classes) during usage and causing problems with the List class, the nodes add/remove functions are either protected or private. This requires that List class is a friend to Node.
However, the problem with this is that the List class itself is a template class for other subclasses, and adding prototyping/adding the friend keyword for each subclass is clearly not the best solution.
How would I design the Node and List class/subclasses so that:
- Node cannot be constructed by itself externally, is only constructed with specific classes/subclasses?
- Node can construct/remove other nodes given above?
- Node functions are only accessible to specific classes (List, list subclasses, and list helper classes – list helper classes are not subclasses of list)?
- The node variable (Item) is publicly accessible give above?
- List, list subclasses and list helper classes can directly modify or indirectly modify the non-public variables of Node?
Are these possible, and if so, how?
I would make
Nodea protected nested class ofList:This way, only List and its subclasses can access it.
Since it is nested withinIt also helps to highlight the functional relationship between the two classes. This probably takes care of all your dot points except the third.List, list may access its private/protected members and functions.EDIT double checking my facts, it seems that in C++ enclosing classes do not have special access permissions to nested class members after all (seems that’s a Java thing), see here. As such, you will need to make
Nodemembers public, but I still think this solution encourages good encapsulation.