This Stack Overflow question is about a child having reference to its parent, through a pointer.Comments were pretty critical initially of the design being a horrible idea.I understand this is probably not the best idea in general. From a general rule of thumb it seems fair to say, don't do this!However, I am wondering what sorts of conditions would exist where you would need to do something like this. This question here and associated answers/commentary suggests even for graphs to not do something like this.
When is a circular reference to a parent pointer acceptable?
design
The key here is not whether two objects have circular references, but whether those references indicate ownership of each other.Two objects cannot own each other: this causes an intractable dilemma for initialization and deletion order. One must be an optional reference, or otherwise indicate that one object will not manage the other's lifetime.Consider a doubly-linked list: two nodes link back and forth to each other, but neither owns the other (the list owns them both). This means neither node allocates memory for the other or is otherwise responsible for the identity or lifetime management of the other.Trees have a similar relationship, although nodes in a tree may allocate children and parents do own children. The link from a child to parent helps with traversal, but again does not define ownership.In most OO designs, a reference to another object as an object's data member implies ownership. For example, suppose we have classes Car and Engine. Neither one is very useful on its own. We can say that these objects depend on each other: they require the presence of the other in order to perform useful work. But which owns the other? In this case we would say that Car owns Engine because the car is the container in which all of the automotive components live. In both an OO and real-world design, the car is the sum of its parts, and all of those parts are connected together within the context of the car. Engine may have a reference back to Car, or it may have a reference to TorqueConverter, but no component inside of Car owns Car even if said component has a reference to the Car.Circular references can be a bad design smell, but not necessarily. When used judiciously and documented correctly, they can make using data structures easier.Try traversing a tree without references going both ways between parents and children. Sure, you could come up with a stack-based approach that is brittle and complex, or you could use the reference-based approach that is trivially simple.