Search code examples
c++code-generationhierarchy

Does generation of implicitly defined member functions get handled independently for every class in a class hierarchy in C++?


Does the presence of a user-defined "Rule of 5" function (destructor, copy constructor, copy-assignment operator, move constructor, or move assignment operator) in a particular class affect whether these functions will get generated in its derived or base classes? If so, in what way?

Put another way, if I'm trying to determine what functions will be implicitly generated for a particular class, do I need information about it's parent or child classes?

Optional Question: Does the presence of one of these functions in a particular class affect the generated code for implicitly generated functions of other classes in the hierarchy? If so, in what way?


Solution

  • The compiler will always declare a destructor for a class C that has no user-declared destructor (C++17 [class.dtor]/4). However, if any base class of C has a deleted or inaccessible constructor, then C's destructor will also be declared as deleted (p5).

    A similar statement holds for copy constructors ([class.copy.ctor]/6) and copy assignment operators ([class.copy.assign]/2).

    In the case of a move constructor, the compiler will only implicitly declare it for a class C if the user did not declare any Rule of 5 functions for C ([class.copy.ctor]/8). The base classes of C can affect whether the move constructor of C is deleted or not, but they do not affect whether the compiler generates a declaration. A similar statement holds for move assignment operators ([class.copy.assign]/4).