Base classes shouldn't have memberwise copy?

Viewed 97

I'm reading Stroustrup's A Tour of C++, and in it there's a line:

To complement =default, we have =delete to indicate that an operation is not to be generated. A base class in a class hierarchy is the classical example where we don't want to allow a memberwise copy.

As someone new to copy/move semantics, I'm having trouble understanding why base classes wouldn't want to have a memberwise copy. I would think that the base class would be responsible for copying its members and the derived class would be responsible for copying the rest. Any examples would be much appreciated.

2 Answers

Because it doesn't always make sense.

If you have a class say, Person with simple fields, it makes sense to have some kind of a default copy/move constructor. It's a data class after all.

Where this breaks down is when your class is operating with some other kind of resource such as streams, database connections, sockets etc, which you don't really want copied - so we prevent errors by telling the compiler not to implement a default copy for this (although a move might be just fine).

On the one hand, it's a good way to prevent accidental slicing, because attempts to do so will result in a compilation error.

On the other, I think you're right: that risk is a small price to pay for the ability to put the various "pieces" of the overall copy operation into the most sensible place. I can't think why I'd want a derived class to be responsible for actioning the copying of base members. Or, come to think of it, perhaps this would prevent the entire hierarchy from being copyable in the first place.

If the base class is completely empty (has no data members, only functions), then I suppose it's more reasonable.

Personally I only ever delete a copy constructor if I want the thing to be non-copyable full stop.

Related