Avoid automatic copy constructor generation
Hi,
is there a way to avoid the automatic copy constructor generation. I do
not want the object to be non-copyable. I simply do not want that
copying is done by the default copy constructor. But there is a
constructor that accepts the base class. This one should be used for
copying.
In fact i have a set of classes with a common abstract base. The
implementations do not have own data members. They only implement
different functionality. But is makes sense to do assignments and copy
construction between these set of types. This effectively changes the
functionality depending on the current type.
class ContainerBase
{ // ...
};
class Container1
: public ContainerBase
{ // no own data members!
public:
Container1()
{}
Container1(const ContainerBase& r)
: ContainerBase(r)
{}
Container1& operator=(const ContainerBase& r)
{ ContainerBase::operator=(r); return *this; }
};
class Container2
: public ContainerBase
{ // no own data members!
public:
Container2()
{}
Container2(const ContainerBase& r)
: ContainerBase(r)
{}
Container2& operator=(const ContainerBase& r)
{ ContainerBase::operator=(r); return *this; }
};
int main()
{ Container1 c1;
Container2 c2 = c1; // OK
Container1 c3 = c1; // Wrong! Invokes Container1(const Contarine1& r)
return 0;
}
Of course, I could implement the copy constructors to do the same thing
as the constructor from const ContainerBase&. But this is really
unneeded redundancy. And the copy constructor is much more complicated
in the real application than in this small example. Furthermore the auto
generated copy constructor is unusable. It has undefined behavior
because of some special internal storage dependencies. It also has to do
with multiple inheritance, so I could not move the code to a member
function either.
Is there a way to avoid the required redefinition of the copy
constructor for each class?
Marcel