In order to emulate a containment relationship in which objects contain other instances of the same type, can I define a class as such?
class RussianDoll {
string name;
RussianDoll doll;
RussianDoll();
}
How should I build the constructor(s) for this class?
Sure. It’s actually quite common. Think of the case of a node in a linked list for instance:
You have several options (see below). You should obviously avoid creating new instances of the class in each invocation of the constructor as it would result in an infinite recursion.
You could take a
Nodeas argument and initialize it likeYou could initialize it to the null-reference
You could initialize it to
this(It’s generally a bad idea to create a whole object graph inside a constructor any way so I wouldn’t worry about this anyway 🙂