    <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  :: Separating Interface and Implementation in C++</title>
        <link>https://members.accu.org/index.php/journals/269</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 #66 - Apr 2005 + 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/c146/">66</a>
                    (7)
<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/c146-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c146+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;Separating Interface and Implementation in C++</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 12 April 2005 18:05:26 +01:00 or Tue, 12 April 2005 18:05:26 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e21" id="d0e21"></a></h2>
</div>
<p>This article discusses three related problems in the design of
C++ classes and surveys five of the solutions to them found in the
literature. These problems and solutions are considered together
because they relate to separating the design choices that are
manifested in the interface from those that are made in
implementing the class. The problems are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Reducing implementation detail exposed to the user</p>
</li>
<li>
<p>Reducing physical coupling</p>
</li>
<li>
<p>Allowing customised implementations</p>
</li>
</ul>
</div>
<p>These have led developers to seek ways to separate interface
from implementation and practice has seen all of the following
idioms used and documented. We will be evaluating them to see how
they compare as solutions to the above problems:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Interface Class</p>
</li>
<li>
<p>Cheshire Cat</p>
</li>
<li>
<p>Delegation</p>
</li>
<li>
<p>Envelope/Letter</p>
</li>
<li>
<p>Non-Virtual Public Interface</p>
</li>
</ul>
</div>
<p>In order to illustrate the problems and solutions we are going
to use a telephone address book (with very limited functionality)
as an example. For comparison purposes we have implemented this as
a na&iuml;ve implementation (see first sidebar) which does not
attempt to address any of the stated problems. We have also
refactored this example to use each of the idioms - the header
files are reproduced in the corresponding sidebars. (The full
implementation and sample client code for all versions of the
example are available with the online version of this article
[<a href="#WEB05">WEB05</a>].)</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e58" id="d0e58"></a>Examining the
Problems</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e61" id="d0e61"></a>Problem 1:
Reducing Implementation Detail Exposed to the User</h3>
</div>
<p>Client code makes use of an object via its public interface,
without any recourse to implementation details. Since the authors
of client code have to use an object through its public interface
that interface is all they need to understand. This public
interface typically comprises member function declarations.</p>
<div class="sidebar">
<p class="title c2">Na&iuml;ve Implementation</p>
<pre class="programlisting">
// naive.h - implementation hiding example.
#ifndef INCLUDED_NAIVE_H
#define INCLUDED_NAIVE_H
#include &lt;string&gt;
#include &lt;utility&gt;
#include &lt;map&gt;

namespace naive {
/** Telephone list. Example of implementing a
*     telephone list using a naive implementation.
*/
class telephone_list {
public:
  /** Create a telephone list.
  * @param    name    The name of the list.
  */
  telephone_list(const std::string&amp; name);

  /** Get the list's name.
  * @return   the list's name.
  */
  std::string get_name() const;

  /** Get a person's phone number.
  * @param    person   Person's name (exact match)
  * @return   pair of success flag and (if success)
  *             number.
  */
  std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const;

  /** Add an entry. If an entry already exists for
  *     this person it is overwritten.
  *   @param  name    The person's name
  *   @param  number  The person's number
  */
  telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number);
private:
  typedef std::map&lt;std::string, std::string&gt; dictionary_t;
  std::string  name;
  dictionary_t dictionary;
  telephone_list(const telephone_list&amp; rhs);
  telephone_list&amp; operator=(const telephone_list&amp; rhs);
};
} // namespace naive
#endif
</pre></div>
<p>C++ allows developers to separate the implementation code for
member functions from the class definition, but there is no
comparable support for separating the member data that implements
an object's state (or, for that matter, for separating the
declarations of private member functions). Consequently the
implementation detail exposed in a class's definition is still
there as background noise, providing users with an added
distraction. The definition of a class is typically encumbered with
implementation &quot;noise&quot; that is of no interest to the user and is
inaccessible to the client code written by that user: the
na&iuml;ve implementation shows this with <tt class=
"varname">MyDict</tt>, <tt class="varname">myName</tt> and
<tt class="varname">dict</tt>.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e82" id="d0e82"></a>Problem 2:
Reducing Physical Coupling</h3>
</div>
<p>The purpose of defining a class in a header file is for the
definition of that class to be included in any translation units
that define the client code for that class. If classes are designed
in a na&iuml;ve manner this leads to compilation dependencies upon
details of the implementation that are not only inaccessible to the
client code but also (in most cases) do not affect it in any
way.</p>
<p>These compilation dependencies are undesirable for two
reasons:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Additional header file inclusions may be required to compile the
class definition. This increases the size of all dependent
translation units. The &quot;Na&iuml;ve Implementation&quot; example needs
<tt class="filename">&lt;map&gt;</tt> even though <tt class=
"classname">std::map</tt> is not used in the public interface - if
this were a user header with its own inclusions these too might be
&quot;bloat&quot;.</p>
</li>
<li>
<p>When changes are made to implementation elements in the header -
even without affecting the interface - the client code must be
recompiled. (When using shared libraries this can also introduce
binary incompatibilities between versions.) Should the example
implementation change the choice of using <tt class=
"varname">MyDict</tt>, <tt class="varname">myName</tt> or
<tt class="varname">dict</tt> this affects all client code.</p>
</li>
</ul>
</div>
<p>In a medium to large system the effect of these compilation
dependencies can multiply to an extent that causes excessive and
problematic build times.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e113" id="d0e113"></a>Problem 3:
Allowing Customised Implementations</h3>
</div>
<p>Library code frequently defines points of customisation for user
code to exploit. One of the ways to do this is to specify an
interface as a class and allow the user code to supply objects that
conform to this interface.</p>
<p>Such a library is typically compiled before the user code is
written. In this case the library contains the &quot;client code&quot; and
for this to have compilation dependencies on the implementation
would be problematic.</p>
<p>Clearly, the na&iuml;ve implementation makes no provision for
alternative implementations.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e122" id="d0e122"></a>The
Idioms</h2>
</div>
<p>We present the best known idioms for implementation hiding along
with some comments in italics.</p>
<p>Each of these idioms can have advantages and these need to be
understood when choosing between them.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e129" id="d0e129"></a>Cheshire
Cat</h3>
</div>
<p>A private &quot;representation&quot; class is written that embodies the
same functionality and interface as the na&iuml;ve class - however,
unlike the na&iuml;ve version, this is defined and implemented
entirely within the implementation file. The public interface of
the class published in the header is unchanged, but the private
implementation details are reduced to a single member variable that
points to an instance of the &quot;representation&quot; class, each of its
member functions forwards to the corresponding function of the
&quot;representation&quot; class.</p>
<p>The term &quot;Cheshire Cat&quot; (see [<a href=
"#Murray1993">Murray1993</a>]) is an old one, coined by John
Carollan over a decade ago. Sadly it seems to have disappeared from
use in contemporary C++ literature. It appears described as a
special case of the Bridge pattern in &quot;Design Patterns&quot; [<a href=
"#GOF95">GOF95</a>], but the name &quot;Cheshire Cat&quot; is not mentioned.
Herb Sutter (in [<a href="#Sut00">Sut00</a>]) discusses it under
the name &quot;Pimpl idiom&quot;, but considers it only from the perspective
if its use in reducing physical dependencies. It has also been
called &quot;Compilation Firewall&quot;.</p>
<p><span class="emphasis"><em>Cheshire Cat requires &quot;boilerplate&quot;
code in the form of forwarding functions (see &quot;Cheshire Cat
Implementation&quot; sidebar below) that are tedious to write and (if
the compiler fails to optimise them away) can introduce a slight
performance hit. It also requires care with the copy semantics
(although it is possible to factor this out into a smart pointer -
see <a href="#Griffiths99">Griffiths99</a>). As the relationship
between the public and implementation classes is not explicit it
can cause maintenance issues.</em></span></p>
<div class="sidebar">
<p class="title c2">Cheshire Cat</p>
<pre class="programlisting">
// cheshire_cat.h  Cheshire Cat -
//           implementation hiding example

#ifndef INCLUDED_CHESHIRE_CAT_H
#define INCLUDED_CHESHIRE_CAT_H
#include &lt;string&gt;
#include &lt;utility&gt;

namespace cheshire_cat {
class telephone_list {
public:
  telephone_list(const std::string&amp; name);
  ~telephone_list();

  std::string get_name() const;

  std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const;

  telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number);
private:
  <span class="bold"><b>class telephone_list_implementation;
  telephone_list_implementation* rep;
  telephone_list(const telephone_list&amp; rhs);
  telephone_list&amp; operator=(
                 const telephone_list&amp; rhs);</b></span>
};
} // namespace cheshire_cat
#endif
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e159" id="d0e159"></a>Delegation</h3>
</div>
<p>One or more areas of the class functionality are factored out
from the na&iuml;ve implementation into separate helper classes.
The class published in the header holds a pointer to each of these
classes and delegates responsibility for the corresponding
functionality by forwarding the corresponding operations. This is
similar to Cheshire Cat, except that some implementation may remain
exposed (like myName in the example) and there may be more than one
helper class. (The helper classes may be defined and implemented in
the implementation file - as in the sample code - or placed in a
header file and made available for use by other code.)</p>
<p><span class="emphasis"><em>Delegation is attractive where there
is a distinct area of functionality that can be factored out or
shared with another class. In maintenance and performance terms it
is similar to Cheshire Cat.</em></span></p>
<div class="sidebar">
<p class="title c2">Delegation</p>
<pre class="programlisting">
// delegation.h - Delegation implementation hiding
//   example.

#ifndef INCLUDED_DELEGATION_H
#define INCLUDED_DELEGATION_H
#include &lt;string&gt;
#include &lt;utility&gt;

namespace delegation {
class telephone_list {
public:
  telephone_list(const std::string&amp; name);
  ~telephone_list();

  std::string get_name() const;

  std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const;

  telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number);
<span class="bold"><b>private:
  std::string name;
  class dictionary;
  dictionary* lookup;
  telephone_list(const telephone_list&amp; rhs);
  telephone_list&amp; operator=(
                 const telephone_list&amp; rhs);</b></span>
};
} // namespace delegation
#endif
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e175" id=
"d0e175"></a>Envelope/Letter</h3>
</div>
<p>As with Cheshire Cat a private &quot;representation&quot; class is written
which implements the same functionality and interface as the
na&iuml;ve class but is defined and implemented entirely within the
implementation file. The variations from Cheshire Cat are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The &quot;representation&quot; class is derived from the public one.</p>
</li>
<li>
<p>The member functions of the public class are declared <tt class=
"literal">virtual</tt> (and overridden in the implementation
class).</p>
</li>
<li>
<p>The class published in the header holds a pointer to what
appears to be another instance of the class but, in fact, is an
instance of the derived class.</p>
</li>
</ul>
</div>
<p>This is described in some detail in Coplien's &quot;Advanced C++
Style and Idioms&quot; [<a href="#Cope92">Cope92</a>].</p>
<p><span class="emphasis"><em>Frankly Envelope/Letter confuses us -
we don't see what advantage it gives over Cheshire Cat. (Maybe it
is just a misguided attempt to represent the correspondence of
interface and implementation functions explicitly?) But please read
Coplien and make up your own mind! In performance terms each client
call initiates two function calls dispatched via the v-table - so
it is the slowest of the idioms. (However it is rare that the
overhead of a virtual function call is
significant.)</em></span></p>
<div class="sidebar">
<p class="title c2">Envelope/Letter</p>
<pre class="programlisting">
// envelope_letter.h - Envelope/Letter
//   implementation hiding example.

#ifndef INCLUDED_ENVELOPE_LETTER_H
#define INCLUDED_ENVELOPE_LETTER_H
#include &lt;string&gt;
#include &lt;utility&gt;

namespace envelope_letter {
class telephone_list {
public:
  telephone_list(const std::string&amp; name);
  virtual ~telephone_list();

  virtual std::string get_name() const;

  virtual std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const;

  virtual telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number);
<span class="bold"><b>protected:
  telephone_list();
private:
  telephone_list* rep;
  telephone_list(const telephone_list&amp; rhs);
  telephone_list&amp; operator=(
                 const telephone_list&amp; rhs);</b></span>
};
} // namespace envelope_letter
#endif
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e209" id="d0e209"></a>Interface
Class</h3>
</div>
<p>All member data is removed from the na&iuml;ve class and all
member functions are made pure virtual. In the implementation file
a derived class is defined that implements these member functions.
The derived class is not used directly by client code, which sees
only a pointer to the public class.</p>
<p>This is described in some detail in Mark Radford's &quot;C++
Interface Classes - An Introduction&quot; [<a href=
"#Radford04">Radford04</a>].</p>
<p><span class="emphasis"><em>Conceptually the Interface Class
idiom is the simplest of those we consider. However, it may be
necessary to provide an additional component and interface in order
to create instances. Interface Classes, being abstract, can not be
instantiated by the client. If a derived &quot;implementation&quot; class
implements the pure virtual member functions of the Interface
Class, then the client can create instances of that class. (But
making the implementation class publicly visible re-introduces
noise.) Alternatively, if the implementation class is provided with
the Interface Class and (presumably) buried in an implementation
file, then provision of an additional instantiation mechanism -
e.g. a factory function - is necessary. This is shown as a static
create function in the corresponding sidebar.</em></span></p>
<p><span class="emphasis"><em>As objects are dynamically allocated
and accessed via pointers this solution requires the client code to
manage the object lifetime. This is not a handicap where the domain
understanding implies objects are to be managed by a smart pointer
(or handle) but it may be significant in some
cases.</em></span></p>
<p><span class="emphasis"><em>Note: Interfaces may play an
additional role in design to that addressed in this article - they
may be used to delineate each of several roles supported by a
concrete type. This allows for client code that depend only on (the
interface to) the relevant role.</em></span></p>
<div class="sidebar">
<p class="title c2">Interface Class</p>
<pre class="programlisting">
// interface_class.h - Interface Class
//   implementation hiding example.

#ifndef INCLUDED_INTERFACE_CLASS_H
#define INCLUDED_INTERFACE_CLASS_H
#include &lt;string&gt;
#include &lt;utility&gt;

namespace interface_class {
class telephone_list {
public:
<span class="bold"><b>  static telephone_list*
                   create(const std::string&amp; name);</b></span>
  virtual ~telephone_list()   {}

  virtual std::string get_name() const = 0;

  virtual std::pair&lt;bool, std::string&gt;
  get_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;
<span class="bold"><b>protected:    
  telephone_list()   {}
  telephone_list(const telephone_list&amp; rhs) {}
private:
  telephone_list&amp; operator=(
                 const telephone_list&amp; rhs);</b></span>
};
} // namespace interface_class
#endif
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e239" id="d0e239"></a>Non-Virtual
Public Interface</h3>
</div>
<p>All member data is removed from the na&iuml;ve class, the public
interface becomes non-virtual forwarding functions that delegate to
corresponding private pure virtual functions. As with Interface
Class the implementation file defines a derived class that
implements these member functions. The derived class is not used
directly by client code, which sees only a pointer to the public
class.</p>
<p>This is described in some detail in Sutter's &quot;Exceptional C++
Style&quot; [<a href="#Sut04">Sut04</a>].</p>
<p><span class="emphasis"><em>We had thought Non-Virtual Public
Interface an idea that had been tried and discarded as introducing
unjustified complexity. While the standard library uses this idiom
in the iostreams design we've yet to see an implementation of the
library that exploits the additional flexibility (in implementing
the public functions) it offers over Interface Class. Further,
there are some costs to providing this flexibility:</em></span></p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="emphasis"><em>A class definition embodies the
contract between code that uses and code that implements that
class. By splitting the contract into (public) non-virtual usage
and (private) virtual implementation parts it introduces a need to
understand both and also a need to document and follow the
relationship between them.</em></span></p>
</li>
<li>
<p><span class="emphasis"><em>There is a development and
maintenance cost: because the implementation functions are private
to the base class they cannot be called directly by a unit
test.</em></span></p>
</li>
<li>
<p><span class="emphasis"><em>There is a potential performance
cost: if the extra function call is not optimised away it can use
additional stack space and time.</em></span></p>
</li>
</ul>
</div>
<div class="sidebar">
<p class="title c2">Non-Virtual Public Interface</p>
<pre class="programlisting">
// non_virtual_public_interface.h - Non-Virtual
//   Public Interface implementation hiding example

#ifndef INCLUDED_NONVIRTUAL_PUBLIC_INTERFACE_H
#define INCLUDED_NONVIRTUAL_PUBLIC_INTERFACE_H
#include &lt;string&gt;
#include &lt;utility&gt;

namespace non_virtual_public_interface {
class telephone_list {
public:
<span class="bold"><b>  static telephone_list* create(
                          const std::string&amp; name);</b></span>
  virtual ~telephone_list() {}

  std::string get_name() const
<span class="bold"><b>    { return do_get_name(); }</b></span>

  std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const
<span class=
"bold"><b>    { return do_get_number(person); }</b></span>

  virtual telephone_list&amp;
  add_entry(const std::string&amp; name, 
            const std::string&amp; number)
<span class="bold"><b>    { return do_add_entry(name, number); }
protected:    
  telephone_list()    {}
  telephone_list(const telephone_list&amp; rhs) {}
private:
  telephone_list&amp; operator=(
                 const telephone_list&amp; rhs);
  virtual std::string do_get_name() const = 0;
  virtual std::pair&lt;bool, std::string&gt;
  do_get_number(const std::string&amp; person) const = 0;
  virtual telephone_list&amp;
  do_add_entry(const std::string&amp; name, 
               const std::string&amp; number) = 0;
</b></span>};
} // namespace non_virtual_public_interface
#endif
</pre></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e282" id="d0e282"></a>Evaluating
the Solutions</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e285" id="d0e285"></a>Problem 1:
Reducing Implementation Detail Exposed to the User</h3>
</div>
<p>All the idioms considered address this problem reasonably
successfully. The only implementation detail any of these idioms
expose is the mechanism by which they support the separation:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Interface Class declares virtual functions</p>
</li>
<li>
<p>Cheshire Cat exposes a pointer to the &quot;real&quot; implementation</p>
</li>
<li>
<p>Non-Virtual Public Interface declares forwarding functions and
virtual functions</p>
</li>
<li>
<p>Envelope/Letter declares virtual functions and a pointer to the
&quot;real&quot; implementation</p>
</li>
</ul>
</div>
<p>Delegation is in a way the odd one out, because it does not by
nature conceal all the implementation detail. This point is
illustrated in our example implementation where the <tt class=
"classname">std::string</tt> member <tt class="varname">myName</tt>
is visible in the definition of <tt class=
"classname">TelephoneList</tt>. Delegation reduces the
implementation noise exposed to clients, but - unless all
functionality is delegated to one (or more) other classes - it
leaves the class still vulnerable to the problems suffered by the
na&iuml;ve implementation.</p>
<div class="sidebar">
<p class="title c2">Cheshire Cat Implementation</p>
<pre class="programlisting">
// MCheshireCat.cpp - implementation hiding example.

#include &quot;cheshire_cat.h&quot;
#include &lt;map&gt;

namespace cheshire_cat {
// Declare the implementation class
class telephone_list::telephone_list_implementation {
public:
  telephone_list_implementation(
                           const std::string&amp; name);
  ~telephone_list_implementation();
  std::string get_name() const;
  std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const;
  void add_entry(const std::string&amp; name,
                 const std::string&amp; number);
private:
  typedef std::map&lt;std::string, std::string&gt;
                                       dictionary_t;
  std::string  name;
  dictionary_t dictionary;
};

// Implement the stubs for the wrapper class
telephone_list::telephone_list(
                            const std::string&amp; name)
   : rep(new telephone_list_implementation(name)) {}

telephone_list::~telephone_list() { delete rep; }

std::string telephone_list::get_name() const {
  return rep-&gt;get_name();
}

std::pair&lt;bool, std::string&gt; telephone_list::
get_number(const std::string&amp; person) const {
  return rep-&gt;get_number(person);
}


telephone_list&amp; telephone_list::add_entry(
                        const std::string&amp; name,
                        const std::string&amp; number) {
  rep-&gt;add_entry(name, number);
  return *this;
}

// Implement the implementation class
telephone_list::telephone_list_implementation::
          telephone_list_implementation(
                            const std::string&amp; name)
   : name(name) {}

telephone_list::telephone_list_implementation::
          ~telephone_list_implementation() {}

std::string telephone_list::
   telephone_list_implementation::get_name() const {
  return name;
}

std::pair&lt;bool, std::string&gt;
telephone_list::telephone_list_implementation::
       get_number(const std::string&amp; person) const {

  dictionary_t::const_iterator i
       = dictionary.find(person);

  return(i != dictionary.end()) ? 
      std::make_pair(true, (*i).second) :
      std::make_pair(true, std::string());
}

void telephone_list::telephone_list_implementation::
add_entry(const std::string&amp; name,
          const std::string&amp; number) {
  dictionary[name] = number;
}
} // namespace cheshire_cat
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e319" id="d0e319"></a>Problem 2:
Reducing Physical Coupling</h3>
</div>
<p>When the principal concern is reducing compile time dependencies
the size (including indirect inclusions) of the header is more
significant than that of the implementation file. However, in most
cases, there is very little difference between the header files
required by the different idioms - in our example they all have the
same includes and the file lengths are as follows:</p>
<pre class="screen">
$ wc *.h | sort
   62    163   1580  cheshire_cat.h
   62    184   1677  interface_class.h
   65    162   1535  naive.h
   66    163   1554  delegation.h
   66    164   1605  envelope_letter.h
   94    285   2688  non_virtual_public_interface.h
</pre>
<p>The lack of variation is not surprising: all of the examples
have eliminated the <tt class="filename">&lt;map&gt;</tt> header
file and the only substantial difference is that Non-Virtual Public
Interface declares twice as many functions (having both public and
private versions of each).</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e331" id="d0e331"></a>Problem 3:
Allowing Customised Implementations</h3>
</div>
<p>It should be noted that only Interface Class and Non-Virtual
Public Interface allow user implementation - the other idioms do
not publish an implementation interface.</p>
<p>When our principal concern is that of simplifying the task of
implementing the class then the size of the implementation file is
most significant:</p>
<pre class="screen">
$ wc interface_class.cpp /
                  non_virtual_public_interface.cpp
   85   147  2013  interface_class.cpp
   89   151  2186  non_virtual_public_interface.cpp
</pre>
<p>There is no substantial difference in implementation cost
between these approaches as they contain almost identical code.</p>
<div class="sidebar">
<p class="title c2">Interface Class Implementation</p>
<pre class="programlisting">
// MAbstractBaseClass.cpp - implementation hiding
// example.
#include &quot;interface_class.h&quot;
#include &lt;map&gt;

// Declare the implementation class
namespace {
class telephone_list_implementation
   : public interface_class::telephone_list {
public:
  telephone_list_implementation(const std::string&amp; name);
  virtual ~telephone_list_implementation();
private:
  virtual std::string get_name() const;
  virtual std::pair&lt;bool, std::string&gt;
  get_number(const std::string&amp; person) const;
  virtual interface_class::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;
  dictionary_t dictionary;
};
} // anonymous namespace

// Implement the stubs for the base class
namespace interface_class {
telephone_list* telephone_list::create(
                          const std::string&amp; name) {
  return new telephone_list_implementation(name);
}
} // namespace interface_class


// Implement the implementation class
namespace {
telephone_list_implementation::
telephone_list_implementation(const std::string&amp; name)
   : name(name) {}

telephone_list_implementation::
~telephone_list_implementation() {}

std::string telephone_list_implementation::get_name() const
  { return name; }

std::pair&lt;bool, std::string&gt;
telephone_list_implementation::
get_number(const std::string&amp; person) const {
  std::pair&lt;bool, std::string&gt; rc(false,
                                  std::string());
  dictionary_t::const_iterator i
      = dictionary.find(person);
  return(i != dictionary.end()) ? 
      std::make_pair(true, (*i).second) :
      std::make_pair(true, std::string());
}

interface_class::telephone_list&amp;
telephone_list_implementation::
add_entry(const std::string&amp; name, const std::string&amp; number) {
  dictionary[name] = number;
  return *this;
}
} // anonymous namespace
</pre></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e347" id=
"d0e347"></a>Conclusion</h2>
</div>
<p>In scenarios where customisation of implementation needs to be
supported the choice is between Interface Class and Non-Virtual
Public Interface. In this case we would prefer the simplicity of
Interface Class (unless we have a need for the public functions to
do more work than forwarding - which leads us into the territory of
TEMPLATE METHOD [<a href="#GOF95">GOF95</a>]).</p>
<p>Sometimes we wish to develop &quot;value based&quot; classes - these can,
for example, be used directly with the standard library containers.
Only three of the idioms (Cheshire Cat, Envelope/Letter and
Delegation) permit this style of class. (Using value-based classes
implies that the identity of class instances is transparent - and
that may not be appropriate). Of these options, Cheshire Cat is
most often the appropriate choice - although Delegation may be
appropriate if it allows common functionality to be factored
out.</p>
<p>There are many occasions where user customisation of
implementation is not required, and the identity of instances of
the class is important. In these circumstances it is reasonable to
expect client code to manage object lifetime explicitly (e.g. by
using a smart pointer). Both Interface Class and Cheshire Cat are
reasonable choices here. Interface Class is simpler, but where a
strong separation of interface and implementation is required
Cheshire Cat may be preferred.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e359" id=
"d0e359"></a>Acknowledgments</h2>
</div>
<p>Thanks to Tim Penhey and Phil Bass for commenting on drafts of
this article.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e364" id="d0e364"></a>References</h2>
</div>
<div class="bibliomixed"><a name="WEB05" id="WEB05"></a>
<p class="bibliomixed">[WEB05] <span class="bibliomisc"><a href=
"http://www.octopull.demon.co.uk/c++/%20implementation_hiding.html"
target="_top">http://www.octopull.demon.co.uk/c++/
implementation_hiding.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Cope92" id="Cope92"></a>
<p class="bibliomixed">[Cope92] J. Coplien. <span class=
"citetitle"><i class="citetitle">Advanced C++ Programming Styles
and Idioms</i></span>, Addison-Wesley, 1992</p>
</div>
<div class="bibliomixed"><a name="Murray1993" id="Murray1993"></a>
<p class="bibliomixed">[Murray1993] Robert B Murray, <span class=
"citetitle"><i class="citetitle">C++ Strategies and
Tactics</i></span>, Addison-Wesley, 1993.</p>
</div>
<div class="bibliomixed"><a name="Sut00" id="Sut00"></a>
<p class="bibliomixed">[Sut00] Herb Sutter. <span class=
"citetitle"><i class="citetitle">Exceptional C++</i></span>,
Addison-Wesley, 2000</p>
</div>
<div class="bibliomixed"><a name="Griffiths99" id=
"Griffiths99"></a>
<p class="bibliomixed">[Griffiths99] <span class=
"bibliomisc"><a href=
"http://www.octopull.demon.co.uk/c++/%20TheGrin.html" target=
"_top">http://www.octopull.demon.co.uk/c++/
TheGrin.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Radford04" id="Radford04"></a>
<p class="bibliomixed">[Radford04] Mark Radford, &quot;C++ Interface
Classes - An Introduction&quot;, <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/%20CPPInterfaceClassesIntro.pdf"
target="_top">http://www.twonine.co.uk/articles/
CPPInterfaceClassesIntro.pdf</a></span></p>
</div>
<div class="bibliomixed"><a name="Sut04" id="Sut04"></a>
<p class="bibliomixed">[Sut04] Herb Sutter. <span class=
"citetitle"><i class="citetitle">Exceptional C++ Style</i></span>,
Addison-Wesley, 2004</p>
</div>
<div class="bibliomixed"><a name="GOF95" id="GOF95"></a>
<p class="bibliomixed">[GOF95] Gamma, Helm, Johnson &amp;
Vlissides. <span class="citetitle"><i class="citetitle">Design
Patterns</i></span>, Addison-Wesley, 1995</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
