问题
Does it make sense to define a copy constructor / operator = in class having pure virtual method or only in derived classes?
回答1:
like normal classes: yes, if you have a specific implementation need.
回答2:
If it has only pure virtual methods (and no data members) then, no, the synthesised one is fine (and won't do anything).
If it does have data members then you should define your own copy constructor if/when it makes sense to do so, just like for any other class. Derived classes don't really have much to do with it.
回答3:
If it is an object you plan on copying, yes, it's a good idea. See my comment below for when it isn't.
If your virtual base class relies on resources that need to be explicitly allocated and copied (buffers, operating system objects, etc.), defining a copy constructor saves you the trouble of doing so in every derived class separately (and, additionally, is something you couldn't do if those base resources were private, using public inheritance).
E.g.:
class Base {
public:
Base( const Base & );
virtual ~Base();
virtual void Method() = 0;
// etc...
private:
int *memberIntArray;
int length;
// etc...
};
class DerivedOne : public Base{
public:
DerivedOne( const DerivedOne & );
virtual ~DerivedOne();
virtual void Method();
// etc...
protected:
// data, etc...
};
class DerivedTwo : public Base{
public:
DerivedTwo( const DerivedTwo & );
virtual ~DerivedTwo();
virtual void Method();
// etc...
protected:
// data, etc...
};
///////////////////
Base::Base( const Base & other ) {
this->length = other.length;
this->memberIntArray = new int[length];
memcpy(this->memberIntArray,other.memberIntArray,length);
}
//etc...
DerivedOne::DerivedOne( const DerivedOne & other )
: Base( other )
{
//etc...
}
DerivedTwo::DerivedTwo( const DerivedTwo & other )
: Base( other )
{
//etc...
}
回答4:
Yes you should.
Rules of having your own implementations for copy constructor, copy assignment operator and destructor for a Class will apply to even an Abstract Class.
Also, have a look at Rule of Three
回答5:
It depends on your usage, if you are not doing anything that requires copying to handled delicately, e.g. copying a handle. You would be better to define a copy constructor in derived classes if required.
来源:https://stackoverflow.com/questions/5593168/abstract-class-copy-constructor