2

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 make X copyable or moveable.

Is there a standard idiom or pattern for dealing with this situation?

3
  • 1
    You could use a tag. struct with_parent {}; X(with_parent, const X& p) : parent(&p) {} - Btw, should't the member variable be const X*?
    – Ted Lyngmo
    Feb 15, 2021 at 22:40
  • Yes it should be const, thanks! Feb 15, 2021 at 22:42
  • What's wrong with taking a pointer as input? Since you are storing a pointer anyway. You only need 1 constructor: class X { const X* parent; public: X(const X* parent = nullptr) : parent(parent) {} }; Feb 15, 2021 at 23:51

1 Answer 1

3

You can use tag dispatching to handle this by creating a tag type that you using to signal you want the construct with pointer to parent behavior instead of copy construction. That would look like

struct parent_reference {};

class X {
    const X* parent;
public:
    // (1) Default constructor with no parent 
    X() : parent(nullptr) {}
    
    // (2) Constructor that accepts a parent
    X(parent_reference, const X& parent) : parent(&parent) {}
            
    // (3) Copy Constructor
    X(const X& that) = default;
};

X a;                       // default
X b(a);                    // copy
X c(parent_reference{}, b) // b is now the parent of c
2
  • Okay, perfect, I think this is the idiom I was looking for! Feb 15, 2021 at 22:43
  • @WillisBlackburn Glad to help. Feb 15, 2021 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.