Reputation: 343
Does it make sense to define a copy constructor / operator = in class having pure virtual method or only in derived classes?
Upvotes: 10
Views: 16859
Reputation: 12829
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...
}
Upvotes: 5
Reputation: 385144
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.
Upvotes: 8
Reputation: 11
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.
Upvotes: 0
Reputation: 206526
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
Upvotes: 0
Reputation: 104698
like normal classes: yes, if you have a specific implementation need.
Upvotes: 6