    <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  :: C++ Interface Classes - Noise Reduction</title>
        <link>https://members.accu.org/index.php/articles/282</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>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #68 - Aug 2005</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/articles/">All</a>

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

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c144/">68</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-144/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+144/">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;C++ Interface Classes - Noise Reduction</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 August 2005 05:00:00 +01:00 or Tue, 02 August 2005 05:00:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Interface classes are a principle mechanism for separating a class' interface from its implementation in C++. I wrote an introduction to interface classes in a previous article.
In this article, I intend to explore interface classes - and their implementation classes - further. </p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p><i class="firstterm">Interface classes</i> are a principle
mechanism for separating a class' interface from its implementation
in C++. I wrote an introduction to interface classes in a previous
article [<a href="#Radford">Radford</a>], and Alan Griffiths and I
included the technique in our survey of techniques for separating
interface and implementation in C++ [<a href=
"#Griffiths-">Griffiths-</a>].</p>
<p>In this article, I intend to explore interface classes - and
their <i class="firstterm">implementation classes</i> - further.
The topics I plan to cover are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>How interface and implementation classes can be designed into
the code in such a way as to reduce implementation &quot;noise&quot;</p>
</li>
<li>
<p>How factory functions can be used to facilitate the above</p>
</li>
<li>
<p>A way of managing instance lifecycles when factory functions are
used to encapsulate different memory allocation mechanisms</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e45" id="d0e45"></a>An Example
Class</h2>
</div>
<p>In [<a href="#Griffiths-">Griffiths-</a>] Alan and I used
<tt class="classname">telephone_list</tt> - a telephone address
book class - in order to illustrate several C++
interface/implementation separation techniques. Here I will again
use (a slightly modified version of) that example.</p>
<p>The <tt class="classname">telephone_list</tt> interface class
looks like this:</p>
<pre class="programlisting">
class telephone_list
{
public:
  virtual ~telephone_list()   {}

  virtual std::string name() const = 0;

  virtual std::pair&lt;bool, std::string&gt;
  number(const std::string&amp; person) const = 0;

  virtual telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number) = 0;

protected:    
  telephone_list() {}
  telephone_list(const telephone_list&amp; rhs) {}
private:
  telephone_list&amp; operator=(const telephone_list&amp; rhs);
};
</pre>
<p>In order for this to have functionality, and in order for
instances to be created, an implementation class is needed - I'm
going to call it <tt class="classname">telephone_list_imp</tt>:</p>
<pre class="programlisting">
class telephone_list_imp : public telephone_list
{
public:
  telephone_list_imp(const std::string&amp; list_name);

private:

  virtual ~telephone_list_imp();

  virtual std::string name() const;

  virtual std::pair&lt;bool, std::string&gt;
  number(const std::string&amp; person) const;

  virtual telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number);

  typedef std::map&lt;std::string, std::string&gt; dictionary_t;

  std::string  name_rep;
  dictionary_t dictionary_rep;

  telephone_list_imp(const telephone_list_imp&amp; rhs);
  telephone_list_imp&amp; operator=(const telephone_list_imp&amp; rhs);
};
</pre>
<p>In [<a href="#Radford">Radford</a>] I also described
implementation only classes, and this is an approach I have applied
here. Apart from the constructors, all member functions have been
made private. This strengthens the separation of interface from
implementation by making it possible to create instances of
<tt class="classname">telephone_list_imp</tt>, while usage must be
via pointers and/or references to <tt class=
"classname">telephone_list</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e81" id="d0e81"></a>Hiding the
Implementation and Creating Instances</h2>
</div>
<p>This whole design is geared up to functionality being used
through pointers/references to <tt class=
"classname">telephone_list</tt>. Therefore, the only reason to make
the definition of <tt class="classname">telephone_list_imp</tt>
visible to client code is so that instances can be created. It
follows that client code has to carry a certain amount of &quot;noise&quot; -
in the form of the publicly visible definition of <tt class=
"classname">telephone_list_imp</tt> - just so instances can be
created.</p>
<p>Further, C++ has the problem of physical dependencies between
header files, and the consequent recompilations that result from
modifications being made to them. This is a consequence of the file
inclusion model inherited from C. Let's say for the sake of an
example, that one day <tt class="classname">telephone_list_imp</tt>
is modified, abandoning the <tt class="classname">std::map</tt>
implementation in favour of a different container. The fact that
client code - which has no dependency on the modified
implementation detail - needs to recompile, emphasises the fact
that <tt class="classname">telephone_list_imp</tt> is just noise to
the client code.</p>
<p>The two issues discussed above add up to the fact that it would
be better if <tt class="classname">telephone_list_imp</tt>'s
definition could be kept out of client code altogether. Ideally,
the best place for the definition of <tt class=
"classname">telephone_list_imp</tt> is in an implementation
(<tt class="filename">typically .cpp</tt>) file. This leads to
another problem of how clients can create instances, but this is
straightforward to solve: in the header file, provide a factory
function for creating instances of <tt class=
"classname">telephone_list_imp</tt>. The header file <tt class=
"filename">telephone_list_imp.h</tt> (with include &quot;guards&quot; removed
for brevity) now looks like this:</p>
<pre class="programlisting">
#include &quot;telephone_list.h&quot;
#include &lt;string&gt;
telephone_list* create_telephone_list(const
    std::string&amp; list_name);
</pre>
<p>Note that there is no mention of the implementation class - the
<tt class="classname">telephone_list</tt> interface class is all
that's needed. In fact, only a forward declaration of <tt class=
"classname">telephone_list</tt> is needed - however, the header
file has been included because users might reasonably expect that
when they write <tt class="literal">#include
&quot;telephone_list_imp.h&quot;</tt> in client code, the base class'
definition will be made available.</p>
<p>The fragment of the implementation file containing the
<tt class="classname">telephone_list_imp</tt> and factory function
definition looks like this:</p>
<pre class="programlisting">
class telephone_list_imp : public telephone_list
{
public:
  telephone_list_imp(const std::string&amp; 
       list_name);

private:

  virtual ~telephone_list_imp();

  virtual std::string name() const;

  virtual std::pair&lt;bool, std::string&gt;
      number(const std::string&amp; person) const;

  virtual telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number);

  typedef std::map&lt;std::string, std::string&gt;
        container;

  std::string  name_rep;
  container dictionary_rep;

  telephone_list_imp
        (const telephone_list_imp&amp; rhs);
  telephone_list_imp&amp; operator=
        (const telephone_list_imp&amp; rhs);
};

telephone_list* create_telephone_list
        (const std::string&amp; list_name)
{
  return new telephone_list_imp(list_name);
}
...
</pre>
<p>At this point in the exercise the aim of removing <tt class=
"classname">telephone_list</tt>'s implementation from having
visibility in client code has been achieved. Clients deal with
pointers/references to <tt class="classname">telephone_list</tt>s,
while <tt class="classname">telephone_list_imp</tt> remains buried
safely in its implementation file. All should be well, but the
solution to one problem has created another.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e154" id="d0e154"></a>How are
Instances Deleted?</h2>
</div>
<p>There are two observations to make about the (&quot;na&iuml;ve&quot;)
implementation of <tt class=
"function">create_telephone_list()</tt>:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The mechanism used to create instances is now encapsulated and
hidden from public view</p>
</li>
<li>
<p>So far, the return type is a simple pointer to
telephone_list</p>
</li>
</ul>
</div>
<p>This means clients can apply the delete operator to pointers
returned from <tt class="function">create_telephone_list()</tt>.
However, they have to rely on documentation to know they must do
this. There is no way it can be made clear in the code, and clients
can't assume it because using the delete operator is not compatible
with all mechanisms for allocating class instances on the heap in
C++. A solution to the problem (not the only one) is, rather than
return a simple pointer, to return a smart pointer such as Boost's
<tt class="classname">shared_ptr</tt> (see [<a href=
"#boost">boost</a>]). The (fragmented form of the) header file
<tt class="filename">telephone_list_imp.h</tt> now looks like
this:</p>
<pre class="programlisting">
#include &quot;telephone_list.h&quot;
#include &quot;boost/shared_ptr.hpp&quot;
#include &lt;string&gt;

boost::shared_ptr&lt;telephone_list&gt; create_telephone_list(const std::string&amp; list_name);
</pre>
<p>While the implementation of <tt class=
"function">create_telephone_list()</tt> now looks like this:</p>
<pre class="programlisting">
boost::shared_ptr&lt;telephone_list&gt; create_telephone_list(const std::string&amp; list_name)
{
  telephone_list* p = new telephone_list_imp(list_name);
  return boost::shared_ptr&lt;telephone_list&gt;(p);
} 
</pre>
<p>In passing note the avoidance of the expression:</p>
<pre class="programlisting">
return boost::shared_ptr&lt;telephone_list&gt;(new telephone_list_imp(list_name));
</pre>
<p>This is because <tt class="classname">boost::shared_ptr</tt>
&quot;remembers&quot; the concrete type created, and uses it when the
instance is deleted - i.e. <tt class=
"classname">telephone_list_imp</tt> having a private destructor
means <tt class="classname">boost::shared_ptr</tt>'s attempt to
delete via it causes a compile error. The mechanism used ensures
that the &quot;remembered&quot; type is <tt class=
"classname">telephone_list</tt>, and thus avoids compilation
problems. Another option is simply to make <tt class=
"classname">telephone_list_imp</tt>'s destructor public. I chose
the option in the code fragment because it adheres to the principle
of all usage being through the interface class.</p>
<p>The above approach solves the problem of deleting the instance
that had its creation mechanism encapsulated. The cost of achieving
this is the hard-wiring of a specific smart pointer into the code.
Further, there is a remaining problem that it doesn't solve.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e215" id="d0e215"></a>Different
Allocation Mechanisms</h2>
</div>
<p>The memory allocation scheme used so far is not the only one
available in C++. For example, the placement form of new could be
used to construct instances in conjunction with using <tt class=
"function">malloc()</tt> to allocate the memory. However, if
<tt class="function">create_telephone_list()</tt> returns a simple
pointer and relies on the client code to apply the delete operator,
then there's no way its implementation can ever be changed to use
an alternative allocation mechanism.</p>
<p>In some design scenarios, as well as having a factory function
to create instances, it is possible to have a disposal function to
delete them. However in the design scenario under consideration,
there is a serious drawback to this approach. The implementation
class <tt class="classname">telephone_list_imp</tt> is implemented
in a way that results in particular complexity characteristics -
i.e. those associated with its implementation container <tt class=
"classname">std::map</tt>. Imagine that there arises a need for a
second implementation with different characteristics. Why this may
be so is outside the scope of this article - suffice to say that if
this is done, <tt class="classname">telephone_list_imp</tt> ceases
to be the only implementation of <tt class=
"classname">telephone_list</tt> in town. Getting back to disposing
of instances, it is not hard to see that in order for clients to
pass instances to a disposal function, either instances of each
implementation class would need to use the same memory allocation
mechanism, or disposal functions would need some way of recovering
the implementation class from a pointer/reference to the interface
class.</p>
<p>The analysis of the complexities and tradeoffs involved in using
disposal function may at some point be the subject of another
article, but in this one I want to look at a different approach.
The approach I want to look at involves associating a disposal
function with class instances at the time their factory function
creates them. Here, just for illustration's sake, is a fragment of
a home grown smart pointer that achieves this:</p>
<pre class="programlisting">
template &lt;typename T&gt; class ref_counted_ptr
{
public:
  ref_counted_ptr(T* p, void (*delete_fn)(T*))
    : pointee(p),
      del(delete_fn)
  {
     ...
  }

  ~ref_counted_ptr() { del(pointee); }

  T* operator-&gt;()
  {
    return pointee;
  }
...
private:
  T* pointee;
  void (*del)(T*);
...
};
</pre>
<p>Using <tt class="classname">ref_counted_ptr</tt>, the
declaration of the factory function now looks like this:</p>
<p>ref_counted_ptr&lt;telephone_list&gt;
create_telephone_list(const std::string&amp; list_name);</p>
<p>Its implementation now looks like this:</p>
<pre class="programlisting">
ref_counted_ptr&lt;telephone_list&gt; 
      create_telephone_list(const std::string&amp; 
      list_name)
{
  telephone_list* mem =
      static_cast&lt;telephone_list*&gt;(std::malloc
      (sizeof telephone_list_imp));

  if (!mem)
    throw std::bad_alloc();

  telephone_list* pobj = new (mem) telephone_list_imp(list_name);

  return ref_counted_ptr&lt;telephone_list&gt;(pobj, del_telephone_list);
}
</pre>
<p>As if by magic, a function called <tt class=
"function">del_telephone_list()</tt> has appeared in the above code
fragment - it looks like this:</p>
<pre class="programlisting">
void del_telephone_list(telephone_list* p)
{
  p-&gt;~telephone_list();
  std::free(p);
}
</pre>
<p>However, as I said, <tt class="classname">ref_counted_ptr</tt>
is for illustration only. There is actually no need to write a
custom smart pointer just to associate a disposal function with a
class instance, because <tt class=
"classname">boost::shared_ptr</tt> has a mechanism for
accommodating a disposal function. Actually, <tt class=
"classname">boost::shared_ptr</tt> has a somewhat more
sophisticated mechanism that allows the disposal function to be
either a pointer to a function, or a function object. For this
article, I'll stick to the approach already used - that of using
<tt class="function">del_telephone_list()</tt> as shown above. The
factory function implementation now looks like this:</p>
<pre class="programlisting">
boost::shared_ptr&lt;telephone_list&gt; create_telephone_list(const std::string&amp; list_name)
{
  telephone_list* mem =
    static_cast&lt;telephone_list*&gt;(std::malloc(sizeof telephone_list_imp));

  if (!mem)
    throw std::bad_alloc();

  telephone_list* pobj = new (mem) telephone_list_imp(list_name);

  return boost::shared_ptr&lt;telephone_list&gt;(pobj, del_telephone_list);
}
</pre>
<p>In passing I should mention that there are various tradeoffs in
possible implementations of reference counted smart pointers, and
<tt class="classname">boost::shared_ptr</tt> addresses only one set
of tradeoffs. I just thought it best to point that out; sorry, but
I'm not going into any more detail on that topic. The reader is
referred to the Boost documentation (see [<a href=
"#boost">boost</a>]).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e286" id="d0e286"></a>Finally</h2>
</div>
<p>Cases where solutions to problems are the solutions are rare -
usually there are alternatives that come with their own sets of
tradeoffs. I hope I have succeeded in making the tradeoffs clear.
This article has covered the three points set out in the
introduction, having followed one train of thought. Others have
been alluded to in passing but not covered, but perhaps in future
articles.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e291" id="d0e291"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Radford" id="Radford"></a>
<p class="bibliomixed">[Radford] Mark Radford, C++ Interface
Classes - An Introduction (<span class="citetitle"><i class=
"citetitle">Overload</i></span> 62, and also available from
<span class="bibliomisc"><a href=
"http://www.twonine.co.uk/articles/CPPInterfaceClassesIntro.pdf"
target=
"_top">http://www.twonine.co.uk/articles/CPPInterfaceClassesIntro.pdf</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Griffiths-" id="Griffiths-"></a>
<p class="bibliomixed">[Griffiths-] Alan Griffiths and Mark
Radford, Separating Interface and Implementation in C++,
(<span class="citetitle"><i class="citetitle">Overload</i></span>,
and also available at <span class="bibliomisc"><a href=
"http://www.twonine.co.uk/articles/SeparatingInterfaceAndImplementation.pdf"
target=
"_top">http://www.twonine.co.uk/articles/SeparatingInterfaceAndImplementation.pdf</a></span>)</p>
</div>
<div class="bibliomixed"><a name="boost" id="boost"></a>
<p class="bibliomixed">[boost] <span class="bibliomisc"><a href=
"http://www.boost.org" target=
"_top">http://www.boost.org</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
