Question

I have a class hierarchy that can be simply put like this:

struct Parent {
    Parent() { }
    Parent(Parent& p, std::string s) { }

private:
    // I want this class to be non-copyable
    Parent(const Parent&);
};

struct Child : public Parent {
    Child() { }
    Child(Parent& p) : Parent(p, "hi") { }
};

When I try to create two instances like this:

Child c1;
Child c2(c1);

I get the following error from Clang:

test.cpp:37:8: error: call to deleted constructor of 'Child'
        Child c2(c1);
              ^  ~~
test.cpp:30:8: note: function has been explicitly marked deleted here
struct Child : public Parent {
       ^
1 error generated.

I want this class to be non-copyable, so is there a way to have the Parent& overload called instead of the copy constructor? I know why it behaves the way it does but I am looking for a workaround. I would like Child(Parent& p) to be called without having to cast it.

I get this error in GCC and Visual Studio as well. I don't get it with Intel's compiler though, but the consistent behaviour of the other three seem to indicate that it's wrong and the others are right.

Was it helpful?

Solution

You're relying on the auto-generated copy constructor of the Child while making the copy constructor of the parent inaccessible. What seems to be happening is that the auto-generated copy constructor for Child is trying to call the copy constructor for the parent, but it can't because it's private.

If you don't want to add in a copy constructor, it looks like you need to either explicitly cast c1 to parent reference:

Child c2(static_cast<Parent&>(c1));

or declare copy constructor for Child.

Apart from that, I don't believe there is a workaround.

OTHER TIPS

You say that you don't want your class to be copyable.

You also say in your question that you want the following snippet to work:

Child c1;
Child c2(c1);

Those requirements are contradictory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top