    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Friend or Foe!</title>
        <link>https://members.accu.org/index.php/journals/2000</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #71 - Feb 2006 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c141/">71</a>
                    (6)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c141-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c141+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Friend or Foe!</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 02 February 2006 22:34:22 +00:00 or Thu, 02 February 2006 22:34:22 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<p>The <code>friend</code> keyword in C++ drops the barriers of access control between a class and functions and/or other classes which are named in the <code>friend</code> declaration. It is a language feature that introductory tutorial text books seem to have a lot of trouble with. In searching for an example of its use, they often reach for that of declaring freestanding operator functions as <code>friend</code>s. In this article, I want to argue the case that using <code>friend</code>s in this way is a bad design decision â€“ albeit for a more subtle reason than any that might immediately spring to mind â€“ and also, that <code>friend</code> is not inherently evil. I will illustrate the latter with an example of how its use does genuinely make a design more robust.</p>
<h2>A Bad Example</h2>
<p>First, letâ€™s dissect a simple example of using <code>friend</code>s to implement <code>operator&lt;&lt;</code> (note that the same arguments can be applied to many similar examples). Consider a simple (and self-explanatory) value based class:</p>
<pre><code>class seconds
{
public:
    explicit seconds(int initialiser);

    //...

    friend std::ostream&amp;
    operator&lt;&lt;(std::ostream&amp; os, const seconds&amp; s);

private:
    int val;
};

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const seconds&amp; s)
{
    os &lt;&lt; s.val;
    return os;
}</code></pre>
<p>The use of <code>friend</code> in this way is, in my experience, fairly common in C++ production code, probably because it is a traditional example used in C++ text books (indeed, no lesser book than <em>C++ Programming Language</em> [1] contains such an example). The immediately obvious way to give <code>operator&lt;&lt;</code> access to the implementation of seconds is to make it a member. However, the <code>operator&lt;&lt;</code> is something of a language design paradox, because there is no way to define it as a class member, while at the same time allowing its idiomatic use in client code. If <code>operator&lt;&lt;</code> were to be defined as a member of the class seconds, then it would not possible to write the simple expression:</p>
<pre><code>std::cout &lt;&lt; seconds(5);</code></pre>
<p>This is because in such expressions it is idiomatic for the instance of the class of which <code>operator&lt;&lt;</code> is a member to appear on the left hand side of the &lt;&lt; operator. If <code>operator&lt;&lt;</code> were made into a member of seconds, the expression would have to be written the other way around. Therefore, a non-member function must be used to implement this operator.</p>
<p>So, whatâ€™s wrong with this approach? Well, one concern is that encapsulation has been breached vis-Ã -vis the use of <code>friend</code>, to allow a non-member function to gain access to the implementation of <code>seconds</code>. However, that is clearly not really a concern (although in my experience many seem to think it is). After all, what really is the difference between a function having (private) implementation access because itâ€™s a member or because itâ€™s a <code>friend</code>? Another way of looking at it is this: a <code>friend</code> function is a member function via a different syntax.</p>
<p>In the above example, the real problem is this: the use of <code>friend</code> to implement a non-member operator is only necessary because a natural (and necessary) conversion is absent from <code>seconds</code>â€™ interface. In such class designs it makes perfect sense for instances to be convertible to a built-in type representation of their value. The addition of the <code>value()</code> member function underpins this, as follows:</p>
<pre><code>class seconds
{
public:
    explicit seconds(int initialiser);

    //...

    int value() const;

private:
    int val;
};

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const seconds&amp; s)

{
    os &lt;&lt; s.value();

    return os;
}</code></pre>
<p>Allowing the value to be converted to a built in type representation via a member function is not only a good thing, it is also necessary in order to make the class usable. For example, a class designer can not know in advance of every conversion client code will need. The provision of the <code>value(</code>) member function allows any required conversion to be added without modifying the definition of <code>seconds</code>. Note the analogy with <code>std::string</code> which permits conversion to <code>const char*</code> via the <code>c_str()</code> member function. Note further, the use of a member function rather than a conversion operator, thus requiring the conversion to be a deliberate decision on the part of <code>seconds</code>â€™ user. </p>
<p>Now <code>operator&lt;&lt;</code> can be implemented as a non-member, and there is no need to use <code>friend</code>. However, I now want to describe a short piece of design work, in which <code>friend</code> is used for the right reasonsâ€¦</p>
<h2>A Persistent Object Framework</h2>
<p>Consider the design of a persistence framework that has the following requirements:</p>
<ul>
<li>The state of certain objects must transcend their existence in a C++ program. Such objects are typically those from the problem (real world) domain. When such objects are not in use in the C++ program, their state is stored in some kind of repository, letâ€™s say, a relational database.</li>
<li>Such objects must be loaded into memory when they are needed, and consigned to the database when they are finished with. For the sake of this example, the loading of objects and their consignment to the database should be transparent to the applications programmer.</li>
</ul>
<p>The housekeeping of whether the object has been retrieved or not is delegated to a (class template) smart pointer called <code>persistent_ptr</code>. <code>persistent_ptr</code> delegates the mechanism used to retrieve objects from the database to the implementations of an interface class called <code>database_query</code>. The definitions look like this:</p>
<pre><code>template &lt;class persistent&gt;
class database_query
{
public:
    typedef persistent persistent_type;
    virtual persistent_type* execute() const = 0;
};

template &lt;typename persistent&gt;
class persistent_ptr
{
public:
    ~persistent_ptr()
    {
        ...
    }

    // ...

    persistent* operator-&gt;()
    {
        return get();
    }

    persistent const* operator-&gt;() const
    {
        return get();
    }

private:
    persistent* get() const
    {
        if (!loaded(object)) object = query-&gt;execute();
            return object;
    }

    boost::scoped_ptr&lt; database_query&lt;persistent&gt; &gt; const query;
    persistent* object;
};

An illustration of persistant_ptrâ€™s use looks like this:

void f()
{
    persistent_ptr object(â€¦);
    :
    :
}</code></pre>
<p>The <code>object</code> is instantiated, its state loaded when/if a call to it is made, and when object goes out of scope its state (if loaded) goes back into the database. The interface class <code>database_query</code> defines the protocol for loading objects from the database into memory. It has just one member function: the <code>execute()</code> function. <code>persistant_ptr</code>â€™s member access operator checks if the object (of type <code>persistent</code>) is loaded and if not, calls the <code>database_query</code>â€™s <code>execute()</code> function, i.e. <em>lazy loading</em> is used and the object is not loaded until it is actually used. Also, the invocation of <code>persistant_ptr</code>â€™s destructor triggers the consigning of <code>persistent</code> to the database. So far so good. However, we are now presented with a problem: what if the <code>database_query</code>â€™s <code>execute()</code> function was to be called (contrary to the idea of this design) by something other than <code>persistent_ptr</code>? One option is just to document that this is not the way this framework is intended to be used. However, it would be much better if this constraint could be stated explicitly by the code itself. There is a way to do thisâ€¦</p>
<h2>A Simple Solution Using friend</h2>
<p>Like many (most?) of the textbook examples of the use of <code>friend</code>, the above example featured its use in accessing private member data. However, member functions too can be made private, and one way to prevent unauthorised parties calling <code>database_query</code>â€™s <code>execute()</code> function is to make it private. This leaves us with a problem: <code>persistent_ptr</code> canâ€™t call it either. One simple solution is to declare <code>persistent_ptr</code> a <code>friend</code>. Given that <code>database_query</code> is an interface class and the execute() function is the only member function, this does not cause any problems with exposure of <em>all</em> private members â€“ a problem normally associated with <code>friend</code>. The interface class <code>database_query</code> now looks like this:</p>
<pre><code>template &lt;class persistent&gt;
class database_query
{
public:
    typedef persistent persistent_type;

private:
    friend class persistent_ptr&lt;persistent&gt;;

    virtual persistent_type* execute() const = 0;
};</code></pre>
<p>Note that there is no impact on derived classes because friendship is not inherited. The use of <code>friend</code> in this way has provided one simple way to bring some extra robustness to the design of this framework.</p>
<h2>Finally</h2>
<p>When designing for C++, occasionally there is a need for two classes to work together closely. In such cases the permitted interactions must often be defined quite specifically, to an extent not covered by the access specifiers public, protected and private. Here, the <code>friend</code> keyword can be an asset. I believe many (most?) of its traditional uses â€“ both in textbook examples and production code â€“ are bad, as illustrated by the <code>seconds</code> example. However, it should not be rejected as bad in every case, as I believe the example of <code>persistent_ptr</code> and its colleague <code>database_query</code> shows.</p>
<p>Mark Radford<br>mark@twonine.co.uk</p>
<h2>References</h2>
<p>1     Stroustrup,Bjarne (1997) C++ Programming Language, 3rd edition, Addison-Wesley.</p>

</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
