Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Contrary to some of the answers there are differences in these two practices.</p> <p>If you put the implementation into the class declaration the method will be automatically marked as <code>inline</code>. For very short methods like wrappers this is a <del>advisable practice</del> very useful feature.</p> <p>If you put the implementation into a separate <code>.cc</code> file you're increasing the readability (as David Titarenco already wrote in his answer) and decreasing possible dependencies in your project. Classes which only occur as references, pointers or return values in the method declaration only need a forward declaration in the header. Their implementation details are irrelevant here and thus for every file including this header too. An example:</p> <pre><code>// test.h class A; // forward declaration of A // #include "decl_of_class_A.h" // not needed here, because ... class B { public: A method1(); // in these cases the forward void method2(A* a); // declaration of A above void method3(A&amp; a); // is completely sufficient. }; </code></pre> <p></p> <pre><code>// test.cc #include "decl_of_class_A.h" // here we really need // the complete declaration of A // in order to be able to *use* it A B::method1() { /*...*/ } // ... </code></pre> <p>Now if you include <code>test.h</code> into another <code>.cc</code> file and the declaration of class <code>A</code> changed, only <code>test.cc</code> need to be recompiled and not the other <code>.cc</code> file. The declaration of the class <code>B</code> didn't change.</p> <p>Besides that: There are situations where you're obliged to put the implementations in your header: If you're writing class or function templates or really want a function being declared as <code>inline</code>.</p> <p>As Omnifarious exactly commented: The attached code you sometimes saw will be surely refused by every C++ compiler. <code>const</code> members of a class must be initialized in an initializer-list. Afterwards they stay fixed and no default assignment operator will be provided for you. This means even if you're using a initializer-list, you'll never be able to write something like that as long as you didn't overload the assignment operator:</p> <pre><code>Point p(10, 20); Point q(0, 0); q = p; // no assignment operator provided ==&gt; error! </code></pre> <p>If you really need constant coordinates you should write <code>const Point p(10, 20)</code>.</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