    <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 - An Introduction</title>
        <link>https://members.accu.org/index.php/articles/233</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 #62 - Aug 2004</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/c150/">62</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+150/">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 - An Introduction</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 August 2004 22:52:10 +01:00 or Sun, 01 August 2004 22:52:10 +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="d0e18" id="d0e18"></a></h2>
</div>
<p>Class hierarchies that have run-time polymorphism as one of
their prominent characteristics are a common design feature in C++
programs, and with good design, it should not be necessary for
users of a class to be concerned with its implementation details.
One of the mechanisms for achieving this objective is the
separation of a class's interface from its implementation. Some
programming languages, e.g. Java, have a mechanism available in the
language for doing this. In Java, an <span class=
"emphasis"><em>interface</em></span> can contain only method
signatures. In C++ however, there is no such first class language
feature, and the mechanisms already in the language must be used to
emulate interfaces as best as can be achieved. To this end, an
<span class="emphasis"><em>interface class</em></span> is a class
used to <span class="emphasis"><em>hoist</em></span> the
polymorphic interface - i.e. pure virtual function declarations -
into a base class. The programmer using a class hierarchy can then
do so via a base class that communicates only the interface of
classes in the hierarchy.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e31" id="d0e31"></a>Example
Hierarchy</h2>
</div>
<p>The much used <span class="emphasis"><em>shape</em></span>
hierarchy example serves well here. Let's assume for the sake of
illustration, that we have two kinds of shape: arc and line. The
hierarchy therefore, contains three <span class=
"emphasis"><em>abstractions</em></span>: the <tt class=
"classname">arc</tt> and <tt class="classname">line</tt> concrete
classes, and the generalisation <tt class="classname">shape</tt>.
From now on, I'll talk mainly about shape and line only - the
latter serving as an illustration of an implementation. These two
classes, in fragment form, look like this:</p>
<pre class="programlisting">
class shape {
public:
  virtual ~shape();
  virtual void move_x(distance x) = 0;
  virtual void move_y(distance y) = 0;
  virtual void rotate(angle rotation) = 0;
  //...
};

class line : public shape {
public:
  virtual ~line();
  virtual void move_x(distance x);
  virtual void move_y(distance y);
  virtual void rotate(angle rotation);
private:
  point end_point_1, end_point_2;
  //...
};
</pre>
<p>The <tt class="classname">shape</tt> abstraction is expressed
here as an <span class="emphasis"><em>interface class</em></span> -
it contains nothing but pure virtual function declarations. This is
as close as we can get in C++ to expressing an interface. Adding to
the terminology, classes such as <tt class="classname">line</tt>
(and <tt class="classname">arc</tt>) are known as <span class=
"emphasis"><em>implementation classes</em></span>.</p>
<p>Now let's assume this hierarchy is to be used in a two
dimensional drawing package. It seems reasonable to suggest that in
this package, <tt class="classname">drawing</tt> may be another
useful abstraction. <tt class="classname">drawing</tt> could be
expressed as an interface class, like in this fragment:</p>
<pre class="programlisting">
class drawing {
public:
  virtual ~drawing();
  virtual void add(shape* additional_shape)
                                          = 0;
  //...
};
</pre>
<p>Besides the virtual destructor, only one member function of
<tt class="classname">drawing</tt> - the <tt class=
"methodname">add()</tt> virtual function - is shown. Note that
<tt class="classname">drawing</tt> does not collaborate with any
implementation of <tt class="classname">shape</tt>, but only with
the interface class <tt class="classname">shape</tt>. This is
sometimes known as <span class="emphasis"><em>abstract
coupling</em></span> - <tt class="classname">drawing</tt> can talk
to any class that supports the <tt class="classname">shape</tt>
interface.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e106" id="d0e106"></a>Benefits</h2>
</div>
<p>Having explained the technique of <span class=
"emphasis"><em>hoisting</em></span> a class's interface, I need to
explain why developers should be interested in doing this. There
are three points:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Hoisting the (common) interface of classes in a run-time
polymorphic hierarchy affords a clear separation of interface from
implementation. Further, doing so helps to underpin the use of
abstraction, because the interface class expresses only the
capabilities of the abstracted entity.</p>
</li>
<li>
<p>It follows on from the above, that new implementations can be
added without changing existing code. For example, it is most
likely that drawing will initially have only one implementation
class, but because other code is dependent only on its interface
class, new implementations <span class=
"emphasis"><em>can</em></span> easily be added in the future.</p>
</li>
<li>
<p>Consider the physical structure of C++ code with regard to the
interface class, its implementation classes, and classes (such as
<tt class="classname">drawing</tt>) that use it. Assuming common
C++ practice is followed, the definition of <tt class=
"classname">shape</tt> will have a header file - let's assume it's
called <tt class="filename">shape.hpp</tt> - all to itself, as will
<tt class="classname">drawing</tt> (i.e. <tt class=
"filename">drawing.hpp</tt>, using the same convention). Now, owing
to the physical structure of C++ (that is, the structure it
inherited from C), if anything in the <tt class=
"filename">shape.hpp</tt> header file is changed, anything that
depends on it - such as <tt class="filename">drawing.hpp</tt> -
must recompile. In large systems where build times are measured in
hours (or even days), this can be a significant overhead. However,
because <tt class="classname">shape</tt> is an interface class,
<tt class="classname">drawing</tt> (for example) has no physical
dependency on any of the implementation detail, and it is in the
implementation detail that change is likely to occur (assuming some
thought has been put into the design of <tt class=
"classname">shape</tt>'s interface).</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e157" id="d0e157"></a>Strengthening
the Separation</h2>
</div>
<p>Returning to the first point above for a moment, there is a way
by which we can strengthen the logical separation further: we can
make <tt class="classname">shape</tt>'s implementation classes into
<span class="emphasis"><em>implementation only</em></span> classes.
This means that in the implementation classes, all the virtual
member functions are made <span class=
"emphasis"><em>private</em></span>, leaving only their constructors
publicly accessible. The <tt class="classname">line</tt> class then
looks like this:</p>
<pre class="programlisting">
class line : public shape {
public:
  line(point end_point_1, point end_point_2);
  //...
private:
  virtual ~line();
  virtual void move_x(distance x);
  virtual void move_y(distance y);
  virtual void rotate(angle rotation);
  //...
};
</pre>
<p>Now, the only thing users can do with <tt class=
"classname">line</tt> is create instances of it. All usage must be
via its interface - i.e. <tt class="classname">shape</tt>, thus
enforcing a stronger interface/implementation separation. Before
leaving this topic, it is important to get something straight: the
point of enforcing the interface/implementation separation is
<span class="emphasis"><em>not</em></span> to tell users what to
do. Rather, the objective is to underpin the logical separation -
the <span class="emphasis"><em>code</em></span> now explains that
the key abstraction is <tt class="classname">shape</tt>, and that
<tt class="classname">line</tt> serves to provide an implementation
of <tt class="classname">shape</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e199" id="d0e199"></a>Mixin
Interfaces</h2>
</div>
<p>As a general design principle, all classes should have
responsibilities that represent a primary design role played by the
class. However, sometimes a class must also express functionality
representing responsibilities that fall outside its primary design
role. In such cases, the need for partitioning of this
functionality is pressing, and interface classes have a part to
play.</p>
<p>A class that expresses this kind of extra functionality is
called a <span class="emphasis"><em>mixin</em></span>. For example,
it is easy to imagine there might be a requirement to store and
retrieve the state of shape objects. However, storage and retrieval
functionality is not a responsibility of shape in the application
domain model. Therefore, a feasible design is as follows:</p>
<pre class="programlisting">
class serialisable {
public:
  virtual void load(istream&amp; in) = 0;
  virtual void save(ostream&amp; out) = 0;
protected:
  ~serialisable();
};

class shape : public serialisable {
public:
  virtual ~shape();
  virtual void move_x(distance x) = 0;
  virtual void move_y(distance y) = 0;
  virtual void rotate(angle rotation) = 0;
  // No declarations of load() or save() in
  // this class
  // ...
};

class line : public shape {
public:
  line(point end_point_1, point end_point_2);
  //...
private:
  virtual ~line();
  virtual void move_x(distance x);
  virtual void move_y(distance y);
  virtual void rotate(angle rotation);
  virtual void load(istream&amp; in);
  virtual void save(ostream&amp; out);
  //...
};
</pre>
<p>This approach is intrusive to a degree because <tt class=
"classname">serialisable</tt>'s virtual member functions must be
declared in <tt class="classname">line</tt>'s interface. However,
at least there is a separation in that <tt class=
"classname">serialisable</tt> is kept separate from the crucial
<tt class="classname">shape</tt> abstraction.</p>
<p>Note that <tt class="classname">serialisable</tt> does not have
a public virtual destructor - its destructor is protected and
non-virtual. It is not intended that pointers to <tt class=
"classname">serialisable</tt> are held and passed around in a
program - i.e. it is not a <span class=
"emphasis"><em>usage</em></span> type, that's the role of the
<tt class="classname">shape</tt> class. Making the destructor
non-virtual and not publicly accessible allows the code to state
this explicitly, without recourse to any further documentation.</p>
<p>Often mixin functionality is added to a class using multiple
inheritance. Here there is an analogy with Java, in which there is
direct language support for interfaces. In Java, a class can
inherit from one other class, but can implement as many interfaces
as desired. The same thing can be emulated in C++ using interface
classes, but in C++ there is an added twist - C++ has <span class=
"emphasis"><em>private</em></span> inheritance to offer. This
approach comes in handy particularly when the usage type is outside
the control of the programmer - for example, because it is part of
a third party API. For example, consider a small framework where
notifications are sent out by objects of type <tt class=
"classname">notifier</tt>, and received by classes supporting an
interface defined by <tt class="classname">notifiable</tt>. The two
interface classes (or fragment of, in the case of <tt class=
"classname">notifier</tt>) are defined as follows:</p>
<pre class="programlisting">
class notifiable {
public:
  virtual void update() = 0;
protected:
  ~notifiable();
};
class notifier {
public:
  virtual void register_client(notifiable* o)
                                          = 0;
  // ...
};
</pre>
<p>Now consider using a GUI toolkit that provides a base class
called window, from which all window classes are to be derived. The
programmer wishes to write a class called my_window that receives
notifications from objects of type <tt class=
"classname">notifier</tt> - such a class could look like this:</p>
<pre class="programlisting">
class my_window : public window,
                  private notifiable {
public:
  void register_for_notifications(
                                notifier&amp; n) {
    n.register_client(this);
  }
  // ...
};
</pre>
<p>Using private inheritance has rendered the notifiable interface
inaccessible to clients, but allows <tt class=
"classname">my_window</tt> use of it, because like anything else
that's private to <tt class="classname">my_window</tt>, its private
base classes are accessible in its member functions. This approach
helps to strengthen the separation of concerns which the use of
mixin functionality seeks to promote.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e270" id="d0e270"></a>Interface
Class Emulation Issues</h2>
</div>
<p>The fact that we have to consider emulation issues at all is
owing to the fact that interfaces are being <span class=
"emphasis"><em>emulated</em></span> rather than being a first class
language feature - all part of the fun of using C++! I think there
are issues in two areas, i.e. those concerned with:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>An interface class's interface</p>
</li>
<li>
<p>Deriving from an interface class</p>
</li>
</ul>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e285" id="d0e285"></a>An Interface
Class's Interface</h3>
</div>
<p>Consider the interface class <tt class=
"classname">shape</tt>:</p>
<pre class="programlisting">
class shape {
public:
  virtual ~shape();
  virtual void move_x(distance x) = 0;
  virtual void move_y(distance y) = 0;
  virtual void rotate(angle rotation) = 0;
  // other virtual function declarations...
};
</pre>
<p>If we write only the above, the compiler will step in and
provide: a copy assignment operator, a default constructor, and a
copy constructor. I think we can safely say that, an interface
class' run time polymorphic behaviour points to assignment
semantics being inappropriate and irrelevant. Therefore, the
assignment operator should be private and not implemented:</p>
<pre class="programlisting">
class shape {
public:
  // ...
private:
  shape&amp; operator=(const shape&amp;);
};
</pre>
<p>Interface classes are stateless by their nature, so allowing
assignment is harmless, but prohibiting it is a simple contribution
to avoiding errors.</p>
<p>What about the default constructor and a copy constructor? Here
we should just thank the compiler and take what is on offer, as
this is the easiest way to avoid any complications. Note that
declaration of constructors by the programmer has potential
pitfalls. For example, if a copy constructor only is declared, then
the compiler will not generate a default constructor.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e303" id="d0e303"></a>Deriving From an
Interface Class</h3>
</div>
<p>Consider the following fragment that shows <tt class=
"classname">line</tt> being derived from <tt class=
"classname">shape</tt> (as one would expect):</p>
<pre class="programlisting">
class line : public shape {
public:
  line(int in_x1, int in_y1,
       int in_x2, int in_y2)
    : x1(in_x1), y1(in_y1),
      x2(in_x2), y2(in_y2) {}
  // ...
private:
  int x1, y1, x2, y2;
};
</pre>
<p>The programmer has declared a constructor that initialises
<tt class="classname">line</tt>'s state, but not specified which of
<tt class="classname">shape</tt>'s constructors is to be called. As
a result the compiler generates a call to <tt class=
"classname">shape</tt>'s default constructor. So far this is fine.
Because <tt class="classname">shape</tt> is stateless it doesn't
matter how it gets initialised.</p>
<p>However, that's not the end of the story ...</p>
<p>It is a common design re-factoring in C++ (and several other
languages), to hoist common state out of concrete classes, and
place it in a base class. So if common implementation is found
between <tt class="classname">shape</tt>'s derived classes
<tt class="classname">line</tt> and <tt class="classname">arc</tt>,
rather than have a two tier hierarchy, it is reasonable to have a
three tier hierarchy. For the sake of an example, let's assume that
it is necessary for all <tt class="classname">shape</tt>s to
maintain a <span class="emphasis"><em>proximity
rectangle</em></span>- i.e. if a point falls within the rectangle,
the point is considered to be in close proximity to the <tt class=
"classname">shape</tt>. This functionality can then, for example,
be used to determine if a <tt class="classname">shape</tt> object
should be selected when the user clicks the mouse near by.</p>
<p>I'm going to assume a suitable <tt class=
"classname">rectangle</tt> class is in scope, and introduce
<tt class="classname">shape_impl</tt> to contain the common
implementation.</p>
<pre class="programlisting">
class shape_impl : public shape {
private:
  virtual ~shape_impl() = 0;
  virtual void move_x(distance x);
  virtual void move_y(distance y);
  virtual void rotate(angle rotation);
  //...
protected:
  shape_impl();
  shape_impl(
          const rectangle&amp; initial_proximity);
  //...
private:
  rectangle proximity;
  // ... 
};
</pre>
<p>The implementation class <tt class="classname">shape_impl</tt>
is abstract, as shown by the pure virtual destructor. As a brief
digression, it is also an <span class="emphasis"><em>implementation
only</em></span> class - its implementation of <tt class=
"classname">shape</tt>'s interface has been declared as private so
clients can create instances, but can't call any of the member
functions.</p>
<p>Now look what happens if <tt class="classname">line</tt>'s base
class is changed, but changing the constructor used to initialise
the base class gets forgotten about.</p>
<pre class="programlisting">
class line : public shape_impl {
public:
  line(int in_x1, int in_y1,
       int in_x2, int in_y2)
    : x1(in_x1), y1(in_y1),
      x2(in_x2), y2(in_y2) {}
  // ...
private:
  int x1, y1, x2, y2;
};
</pre>
<p>This will compile, and fail at run time. However, if in the
first place the programmer had written:</p>
<pre class="programlisting">
class line : public shape {
public:
  line(int in_x1, int in_y1,
       int in_x2, int in_y2)
    : shape(), x1(in_x1), y1(in_y1),
      x2(in_x2), y2(in_y2) {}
  // ...
};
</pre>
<p>In the latter case, changing the base class to <tt class=
"classname">shape_impl</tt> would cause a compile error, because
<tt class="classname">shape</tt> is no longer the immediate base
class. This leads me to make the following recommendation:
<span class="emphasis"><em>always call an interface class's
constructor explicitly</em></span>.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e398" id="d0e398"></a>Finally</h2>
</div>
<p>Interface classes are fundamental to programming with run time
polymorphism in C++. Despite this, I'm all too frequently surprised
by how little they are known about by the C++ programmers out
there.</p>
<p>This article doesn't cover everything: for example, the use of
virtual inheritance when deriving from mixins is something I hope
to get around to covering in a future article. However, I hope this
article serves as a reasonable introduction.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e405" id=
"d0e405"></a>Acknowledgements</h2>
</div>
<p>Many thanks to Phil Bass, Thaddaeus Frogley and Alan Griffiths
for their feedback.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
