Does it make sense to define a copy constructor / operator = in class having pure virtual method or only in derived classes?
5 Answers
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.

- 378,754
- 76
- 643
- 1,055
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...
}

- 12,499
- 5
- 45
- 60
-
I would just add that a copy constructor should be used in favor of overriding the = operator. It improves readability and is less error-prone. – janhink Apr 08 '11 at 09:41
-
7I honestly prefer to declare private empty copy constructors and assignment operators to everything. This way, if I ever try to copy something inappropriately, the compiler complains. Only if I really actually *need* a copyable object do I expose any of that. You might laugh reading that, but you'd be surprised how many problems were fixed when I started that practice. ;) – Nate Apr 08 '11 at 09:55
-
@nate or you can use `= delete` – Erik Aronesty Feb 05 '20 at 14:30
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
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.

- 11
- 3