Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ copy constructor - implicit copy for all but one field?

Supose I have a class containing many fields, and/or is constantly changing (in development), and all its fields are either natives or of not-necessarily-POD types which provide a satisfactory copy-constructor, but one - which might has even deleted or privatize its copy-constructor, yet provides me with ways of doing the copy as I need.
Now suppose I need it to have a copy-constructor of its own.
Am I bound to write the exhaustive (exhausting) field by field copy, or is there a cleaner, less exposed to bugs, way to achieve the same goal?

illustration code :

class Big {
public :
  Big(Big const & big) : ? { ? }
protected :
  int i1, i2, ... , i50;
  float f1, f2, ... , f50;
  CopyConstructableClass1 c1;
  CopyConstructableClass2 c2;
  ...
  CopyConstructableClass20 c20;
  NonCopyConstructableClass ncc;
};

Thanks

like image 916
elad Avatar asked Nov 30 '15 21:11

elad


2 Answers

You could wrap the obnoxious class in question into a sanely copyable class of your own design, and then make the field in your big, changing class to be of that wrapper type rather than the original type. That way you only need to do the work of the "custom copying" once in one place, and you can reuse that logic later elsewhere.

This is following the single responsibility principle, which states that every class should have precisely one responsibility, and complexity is built by composition.

like image 189
Kerrek SB Avatar answered Oct 14 '22 18:10

Kerrek SB


Usually what I do in this case is to put all the fields which can copy themselves into base class. Than I can have a derived class with just one field, which will be copied manually.

To emphasize the fact that this base class is not to be used on it's own, it is prudent to mark it's destructor protected. Actually, all of it's members can be.

like image 34
SergeyA Avatar answered Oct 14 '22 18:10

SergeyA