Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The main practical difference is that if the member function definitions are in the body of the header, then of course they are compiled once for each translation unit which includes that header. When your project contains a few hundred or thousand source files, and the class in question is fairly widely used, this might mean a lot of repetition. Even if each class is only used by 2 or 3 others, the more code in the header, the more work to do.</p> <p>If the member function definitions are in a translation unit (.cpp file) of their own, then they are compiled once, and only the function declarations are compiled multiple times.</p> <p>It's true that member functions defined (not just declared) in the class definition are implicitly <code>inline</code>. But <code>inline</code> doesn't mean what people might reasonably guess it means. <code>inline</code> says that it's legal for multiple definitions of the function to appear in different translation units, and later be linked together. This is necessary if the class is in a header file that different source files are going to use, so the language tries to be helpful.</p> <p><code>inline</code> is also a hint to the compiler that the function could usefully be inlined, but despite the name, that's optional. The more sophisticated your compiler is, the better it is able to make its own decisions about inlining, and the less need it has for hints. More important than the actual inline tag is whether the function is available to the compiler at all. If the function is defined in a different translation unit, then it isn't available when the call to it is compiled, and so if anything is going to inline the call then it's going to have to be the linker, not the compiler.</p> <p>You might be able to see the differences better by considering a third possible way of doing it:</p> <pre><code>// File class.h class MyClass { private: //attributes public: void method1(...); void method2(...); ... }; inline void MyClass::method1(...) { //implementation } inline void MyClass::method2(...) { //implementation } </code></pre> <p>Now that the implicit inline is out of the way, there remain some differences between this "all header" approach, and the "header plus source" approach. How you divide your code among translation units has consequences for what happens as it's built.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload