c++header-fileskeyword

Which keywords from the header go into the cpp file?


If I split the code into .h and .cpp files, which of the following keywords used in the header must also be used in the .cpp file and which must not go into the .cpp file:

const, virtual, override, noexcept, constexpr

and in which order do they have to be used, i.e. is the following order correct:

virtual constexpr int foo() const override noexcept;

Please feel free to give a rule if such exists.


Solution

  • The "virtual" specifiers are part of the class definition and only belong on the class member specification, which in this case is the declaration (with or without definition) of a non-static class member function. A member being "virtual" is a property of the class, not of the function type.

    The "qualifiers" (const, volatile, &, &&) and the constexpr/consteval specifiers are part of the function, and thus must appear on every declaration of the (member) function (including the defining one, regardless of whether that's inline or out of line):

    // Class definition of X; specifies the members of X.
    struct X : Base {
      virtual void f() const;  // virtual and override
      void g() && override;    // are part of "being a member"
    };
    
    // Function declarations and definitions:
    // qualifiers are part of the function.
    void X::f() const { /* ... */ }
    void X::g() &&    { /* ... */ }
    

    This has nothing to do with .h and .cpp files per se, though one would typically place an out-of-line definition into a .cpp file. (If it were left in a header, it would lead to repeated definitions when the header is included in different translation units, unless one of the declarations were also explicitly specified as inline. By contrast, inline definitions of class member functions are implicitly inline.)