Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In general, you should probably prefer free functions. Think about it from an OOP perspective.</p> <p>If the function does not need access to any private members, then why should it be <em>given</em> access to them? That's not good for encapsulation. It means more code that may potentially fail when the internals of the class is modified.</p> <p>It also limits the possible amount of code reuse.</p> <p>If you wrote the function as something like this:</p> <pre><code>template &lt;typename T&gt; bool getSelectedDocs(T&amp; container, std::vector&lt;Doc*&gt;&amp;); </code></pre> <p>Then the same implementation of getSelectedDocs will work for <em>any</em> class that exposes the required functions, not just your DocContainer.</p> <p>Of course, if you don't like templates, an interface could be used, and then it'd still work for any class that implemented this interface.</p> <p>On the other hand, if it is a member function, then it'll only work for this particular class (and possibly derived classes).</p> <p>The C++ standard library follows the same approach. Consider <code>std::find</code>, for example, which is made a free function for this precise reason. It doesn't need to know the internals of the class it's searching in. It just needs <em>some</em> implementation that fulfills its requirements. Which means that the same <code>find()</code> implementation can work on any container, in the standard library or elsewhere.</p> <p>Scott Meyers argues for the <a href="http://www.ddj.com/cpp/184401197" rel="nofollow noreferrer">same thing</a>.</p> <p>If you don't like it cluttering up your main namespace, you can of course put it into a separate namespace with functionality for this particular class.</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