Short answer: Yes, you will need to repeat work in D
Long answer:
If your derived class 'D' does not contain new member variables, then the default versions (generated by the compiler should work just fine). The default copy constructor will invoke the parent copy constructor, and the default assignment operator will invoke the parent assignment.
But if your class โDโ contains resources, you will need to do some work.
I find your copy constructor a bit strange:
B(const B& b){(*this) = b;} D(const D& d){(*this) = d;}
Usually copy the chain of constructors so that they are copied from the base up. Here, since you invoke the assignment operator, the copy constructor must invoke the default constructor, which by default initializes the object first from the bottom up. Then you go down again with the assignment operator. It seems rather inefficient.
Now, if you are doing the job, you are copying from bottom to top (or top to bottom), but it is difficult for you to do this and provide a reliable guarantee of exclusion. If at any moment the resource cannot copy and you selected an exception, the object will be in an undefined state (which is bad).
Usually I saw how it was done the other way around.
The assignment operator is defined in terms of the copy and swap constructor. This is because it makes it easier to provide a reliable guarantee of exclusion. I do not think that you can provide a strong guarantee by doing so (I may be wrong).
class X {
Even if you get class D from X, this does not affect this pattern.
Admittedly, you need to repeat the work a bit by making explicit calls to the base class, but this is relatively trivial.
class D: public X {
Loki Astari Aug 04 '09 at 10:39 2009-08-04 10:39
source share