I have been learning about destructors, copy constructors, move constructors, and the rest. I also learned the recommendation about marking your destructor as virtual in a base class that has derived classes inheriting from it.
According to the Rule of Five, if I define a destructor within a class, I should also define the copy constructor and assignment operator, as well as the move constructor and assignment operator within the class.
My question about the Rule of Five is in relation to Inheritance and Polymorphism. If I create a base class that has derived classes inheriting from it, would the Rule of Five only apply to the base class, or would it also apply to the derived classes as well?
What the base class does (what special members it customizes) doesn't affect the rule of 3/5/0 for the derived class. The derived class should use the rule of zero, if it doesn't need to customize the special members for itself.
Note that merely adding a virtual destructor does count as customizing it for the purposes of the rule of 3/5/0, meaning you have to follow the rule of 3/5 for that class.
But the reason is not obvious: Declaring any destructor (doesn't matter if =default
or not) strips you of move operations, leaving only copy operations. This silently replaces all moves of your class with copies, which isn't good. (This doesn't affect derived classes, those are still moved, except for the base class subobject in them.)
=default
ing move operations to bring them back then removes the copy operations, which need to be =default
ed as well.
The above would only matter for classes with data members (that benefit from being moved), but there's another problem: The fact that the copy operations remain when declaring a destructor is deprecated, they should disappear like the move operations do.
This means that if you have a virtual destructor, you have to =default
the copy and move operations even if you don't have data members, to avoid deprecation warnings (build with -Wdeprecated
to enable them).