I am writing a class that can optionally have a reference to its parent. In other words the class looks something like this:
class X {
const X* parent;
public:
// (1) Default constructor with no parent
X() : parent(nullptr) {}
// (2) Constructor that accepts a parent
X(const X& parent) : parent(&parent) {}
};
The problem is that constructor 2 is the copy constructor, but it's not working as a copy constructor.
Obviously I could just have constructor 2 take a pointer. Another solution could be to make a static method to construct a new X
and set its parent
member.
Every solution has annoying drawbacks:
- Possibly constructor does something with parent so if I passed it as a pointer I'd have to handle the
nullptr
case at runtime. - If I create a static function to initialize an
X
with a parent, then I have to makeX
copyable or moveable.
Is there a standard idiom or pattern for dealing with this situation?
struct with_parent {};
X(with_parent, const X& p) : parent(&p) {}
- Btw, should't the member variable beconst X*
?const
, thanks!class X { const X* parent; public: X(const X* parent = nullptr) : parent(parent) {} };