Deep copy and inheritance can work together, but special care must be provided. Let us consider the following subclass of Y:
The default constructor of Y is invoked implicitly first when the default constructor of Z is invoked. There is nothing for us to do here. The same applies to destructors. The destructor of A is implicitly invoked after the destructor of B is done.
The problems are with the copy constructor and the assignment operators. Both of these methods need to explicitly refer to the matching methods of class Y. As a result, we have the following definitions:
Note that there is an implicit up casting on line 14. This is fine, because we are passing it by a reference to const Y. The clone methods are all protected (not private) because subclasses of Y need to use Y::clone, and subclasses of Z need to access Z::clone.
This propagation of clone operations cannot be enforced by the compiler. In other words, the programmer is responsible to ensure that each subclass implementa the copy constructor and assignment operator correctly.