    <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  :: Programming with Interfaces in C++</title>
        <link>https://members.accu.org/index.php/journals/471</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 #40 - Dec 2000 + Design of applications and programs</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/c164/">40</a>
                    (5)
<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/c67/">Design</a>
                    (236)
<br />

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

                    -                        <a href="https://members.accu.org/index.php/journals/c164+67/">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;Programming with Interfaces in C++</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 December 2000 16:46:04 +00:00 or Tue, 26 December 2000 16:46:04 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
<h3>A New Approach</h3>
</div>
<p>This article grew out of an email exchange concerning an article
in Bill Venners's column in the online magazine Javaworld. You can
read the full article at <a href=
"http://www.javaworld.com/%20javaworld/jw-12-1998/jw-12-techniques.html"
target="_top">www.javaworld.com/
javaworld/jw-12-1998/jw-12-techniques.html</a>, though I will
summarise its main points here. Venners also maintains a discussion
group for his articles, and the follow-up postings can be found at
<a href=
"http://www.artima.com/flexiblejava/fjf/interfaces/index.html"
target=
"_top">www.artima.com/flexiblejava/fjf/interfaces/index.html</a>.</p>
<p>The gist of the article - and by all means go read the original,
because I do not want to twist Bill's words - is that Java, with
its concept of interfaces as a major language feature, leads to
better design and implementation than C++.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e32" id="d0e32"></a>Interface vs
Implementation</h2>
</div>
<p>In the beginning, says Venners, he looked on Java <tt class=
"literal">interface</tt>s as a halfway version of multiple
inheritance. Although he was sure the Java solution was superior,
he could not really say why:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;Prior to the advent of Java, I spent five years programming in
C++, and in all that time I had never once used multiple
inheritance. Multiple inheritance wasn't against my religion
exactly, I just never encountered a C++ design situation where I
felt it made sense. When I started working with Java, what first
jumped out at me about interfaces was how often they were useful to
me. In contrast to multiple inheritance in C++, which in five years
I never used, I was using Java's interfaces all the time.</p>
<p>&quot;So given how often I found interfaces useful when I began
working with Java, I knew something was going on. But what,
exactly? Could Java's interface be solving an inherent problem in
traditional multiple inheritance? Was multiple inheritance of
interface somehow intrinsically better than plain, old multiple
inheritance?&quot;</p>
</blockquote>
</div>
<p>The article then launches into a detailed explanation of the
'diamond problem', which arises when two classes inherit from the
same base class, and then a fourth class inherits from both of the
derived classes. The strange hierarchy below relates to the movie
Jurassic Park, where frog DNA was used to fill out incomplete
dinosaur DNA:</p>
<pre class="programlisting">
abstract class Animal 
{
  abstract void talk();
}
class Frog extends Animal 
{
  void talk() { System.out.println(&quot;Ribit, ribit.&quot;); }
}
class Dinosaur extends Animal 
{
  void talk() 
  { 
    System.out.println(
     &quot;Oh I'm a dinosaur and I'm OK...&quot;);
  }
}
// (This won't compile, of course -
// Java only supports single 
// inheritance.)
class Frogosaur extends Frog, Dinosaur {
}
</pre>
<p>The diamond problem rears its ugly head when someone tries to
invoke <tt class="methodname">talk()</tt> on a <tt class=
"classname">Frogosaur</tt> object from an <tt class=
"classname">Animal</tt> reference, as in:</p>
<pre class="programlisting">
Animal animal = new Frogosaur();
animal.talk();  //[ambiguous call - lg]
</pre>
<p>This was the first argument that annoyed me. I would agree that
multiple inheritance in C++, even with completely abstract base
classes to avoid the &quot;burden&quot; of multiple inheritance of
implementation, is a feature best used sparingly. But I think Java
devotees make too much of the dreaded diamond inheritance problem.
Multiple inheritance is an elegant expression of a situation where
a class logically inherits features from two different domains. The
diamond situation rarely arises, and when it does, it should prompt
a re-think of the design. But too many Java-centric articles imply
that the mere existence of multiple inheritance in C++ must
inevitably lead to clumsy design and kludgy implementations.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e64" id="d0e64"></a>Polymorphism is
Key</h2>
</div>
<p>But to get back to the Venners article, he goes on to describe
what he sees as the real advantage of interfaces in Java:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;As time went by I began to believe that the key insight into
the interface was not so much about multiple inheritance as it was
about polymorphism ... Java's interface gives you more polymorphism
than you can get with singly inherited families of classes, without
the 'burden' of multiple inheritance of implementation.&quot;</p>
</blockquote>
</div>
<p>Polymorphism, of course, refers to the ability of any object of
a derived class to function as a substitute for its parent class,
and do so in an appropriate way. All <tt class=
"classname">Animal</tt>s have certain common behaviours, although
they may perform them differently - a dog will bark, a cat will
meow, a hamster will squeak, and so forth. The appropriate
behaviour is determined at runtime through the magic of dynamic
binding, based on the actual type of the object involved.</p>
<pre class="programlisting">
interface Talkative 
{
  void talk();
}
abstract class Animal 
  implements Talkative 
{
  abstract public void talk();
}

class Dog extends Animal 
{
  public void talk() 
  {   
    System.out.println(&quot;Woof!&quot;); 
  }
}
class Cat extends Animal 
{
  public void talk() 
  { 
    System.out.println(&quot;Meow.&quot;);
  }
}
class Interrogator 
{
  static void 
  makeItTalk(Talkative subject) 
  { 
    subject.talk(); 
  }
}
</pre>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;Given this set of classes and interfaces, later you can add a
new class to a completely different family of classes and still
pass instances of the new class to <tt class=
"methodname">makeItTalk()</tt>.&quot;</p>
</blockquote>
</div>
<pre class="programlisting">
class CuckooClock implements Talkative 
{
  public void talk() 
  { 
    System.out.println(&quot;Cuckoo,cuckoo!&quot;);
  }
}
class Example4 {
  public static void main(String[] args)
  {
    CuckooClock cc = new CuckooClock();
    Interrogator.makeItTalk(cc);
  }
}
</pre>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;With single inheritance only, you'd either have to somehow fit
<tt class="classname">CuckooClock</tt> into the <tt class=
"classname">Animal</tt> family, or not use polymorphism. With
interfaces, any class in any family can implement <tt class=
"classname">Talkative</tt> and be passed to <tt class=
"methodname">makeItTalk()</tt>. This is why I say interfaces give
you more polymorphism than you can get with singly inherited
families of classes.&quot;</p>
</blockquote>
</div>
<p>In later messages to the discussion group, Venners adds that his
experience in using Java interfaces would now lead him to make
greater use of abstract base classes, if he were writing C++. Sigh.
So many authors refer to C++ as it was more than five years ago.
They overlook that modern C++ has an excellent mechanism for
providing non-inheritance-based polymorphism, through the use of
templates.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e104" id="d0e104"></a>Templates as
Interfaces</h2>
</div>
<p>The C++ idiom to express the <tt class=
"classname">Talkative</tt> interface discussed in Venners's article
would look something like this:</p>
<pre class="programlisting">
template &lt;class T&gt;
class Talkative 
{
  T const &amp; t;
public:
  Talkative(T const &amp; obj) : t(obj) { }
  void talk() const { t.talk(); }
};
</pre>
<p>This template enables any class which defines a <tt class=
"methodname">talk()</tt> method to be used where a <tt class=
"classname">Talkative</tt> type is needed:</p>
<pre class="programlisting">
Talkative&lt;Dog&gt; td( aDog );
td.talk();
Talkative&lt;CuckooClock&gt; tcc(aCuckooClock);
tcc.talk();
</pre>
<p>Better yet, even classes which <span class=
"emphasis"><em>don't</em></span> have a <tt class=
"methodname">talk()</tt> method, but which provide equivalent
functionality, can be made <tt class="classname">Talkative</tt>
through user-defined specialisation:</p>
<pre class="programlisting">
template&lt;&gt;
void Talkative&lt;BigBenClock&gt;::talk() 
{
  t.playBongs(); 
}
</pre>
<p>Also through specialisation, missing functionality can be added,
without affecting the original class code:</p>
<pre class="programlisting">
template&lt;&gt;
void Talkative&lt;SilentClock&gt;::talk() 
{ 
  cout &lt;&lt; &quot;tick tock&quot; &lt;&lt; endl; 
}
</pre>
<p>There is one way in which Java interfaces are somewhat more
convenient than C++ template classes. You can use interfaces as
formal parameters to a function, and any class which implements
that interface can be passed as an argument. Because there is no
implicit relationship between instantiated templates in C++, you
either have to use a template function (like <tt class=
"methodname">makeItTalk</tt>), or derive the <tt class=
"classname">Talkative</tt> template from a non-template base class,
and use that as the parameter type. However, flexibility can be
achieved by relying on the C++ compiler's ability to deduce
template arguments from an appropriate adapter function:</p>
<pre class="programlisting">
template &lt;class T&gt; 
void makeItTalk( Talkative&lt;T&gt; t )
{ 
  t.talk(); 
}
template &lt;class T&gt; 
Talkative&lt;T&gt; makeTalkative( T&amp; obj )
{
   return Talkative&lt;T&gt;( obj ); 
}
</pre>
<p>Thus:</p>
<pre class="programlisting">
makeTalkative( aDog ).talk();
makeItTalk(makeTalkative(aBigBenClock));
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e155" id="d0e155"></a>Improved Code
Management</h2>
</div>
<p>You could argue that adding '<tt class="literal">implements
Talkative</tt>' to the class definition is useful for documentation
purposes. But you could also argue that it is intrusive on the
design of domain classes, and modifying source code which you do
not 'own' or which others share is sometimes undesirable or
impossible for various reasons.</p>
<p>Creating a new Java subclass to add <tt class=
"classname">Talkative</tt>-ness to some domain object can be
impossible if most classes are declared <tt class=
"literal">final</tt> (as was recommended by another article in
JavaWorld). If an unrelated <tt class="function">talk()</tt>
function is defined by some class in the hierarchy, overriding that
function to implement the <tt class="classname">Talkative</tt>
interface could break existing code. These are issues that become
more important as Java is used in larger, real-world projects. The
C++ template approach has the advantage that polymorphism can be
attached to a class object without requiring any change to that
class's code.</p>
<p>As an additional advantage, template classes can define member
variables and functionality not related to the class of the
template argument. They are like interfaces that can be attached to
objects for limited purposes and periods of time. And they add no
overhead to the size of the object in memory, as abstract virtual
base classes would.</p>
<p>There are proposals going through the Java Community Process to
add support for &quot;notions of genericity based on parametric
polymorphism&quot; (translation: some form of templates) to the Java
language. You can read more about this proposal at <a href=
"http://java.sun.com/aboutJava/communityprocess/jsr/jsr_014_gener.html"
target=
"_top">java.sun.com/aboutJava/communityprocess/jsr/jsr_014_gener.html</a>.</p>
<p>Here is the example program:</p>
<pre class="programlisting">
// talkativ.cpp
#include &lt;iostream&gt;
using std::cout;
using std::endl;
// some domain objects
class Dog 
{
public:
  void talk() const  
  { 
    cout &lt;&lt; &quot;woof woof&quot; &lt;&lt; endl; 
  }
};
class CuckooClock 
{
public:
  void talk() const 
  { 
    cout &lt;&lt; &quot;cuckoo cuckoo&quot; &lt;&lt; endl; 
  }
};
class BigBenClock 
{
public:
  void talk() const 
  { 
    cout&lt;&lt;&quot;take a long tea-break&quot;&lt;&lt;endl;
  }
  void playBongs() const 
  { 
    cout &lt;&lt;&quot;bing bong bing bong&quot; &lt;&lt;endl; 
  }
};
class SilentClock 
{
// doesn't talk
};
// generic template to provide 
// non-inheritance-based polymorphism
template &lt;class T&gt; 
class Talkative 
{
  T const &amp; t;
public:
  Talkative(T const &amp; obj) : t(obj) { }
  void talk() const { t.talk(); }
};
// specialization to adapt functionality
template &lt;&gt; class Talkative&lt;BigBenClock&gt; {
  BigBenClock const &amp; t;
public:
  Talkative(BigBenClock&amp; obj) : t(obj){}
  void talk() const { t.playBongs(); }
};
// specialization to add missing 
// functionality
template &lt;&gt; class 
Talkative&lt;SilentClock&gt; 
{
  SilentClock const &amp; t;
public:
  Talkative(SilentClock&amp; obj): t(obj) {}
  void talk() const 
{ 
      cout &lt;&lt; &quot;tick tock&quot; &lt;&lt; endl; 
  }
};
// adapter function to simplify syntax
// in usage
template &lt;class T&gt; 
Talkative&lt;T&gt; makeTalkative( T&amp; obj ) 
{
  return Talkative&lt;T&gt;( obj );
}
// function to use an object which
// implements the Talkative interface,
// C++ style
template &lt;class T&gt; 
void makeItTalk(Talkative&lt;T&gt;t){t.talk();}
// test program
int main() 
{
  Dog aDog;
  CuckooClock aCuckooClock;
  BigBenClock aBigBenClock;
  SilentClock aSilentClock;
  Talkative&lt;Dog&gt; td(aDog);
  td.talk();
  Talkative&lt;CuckooClock&gt; 
                  tcc(aCuckooClock);
  tcc.talk();
  makeTalkative(aDog).talk();
  makeTalkative(aCuckooClock).talk();
  makeItTalk(makeTalkative(aBigBenClock));
  makeItTalk(makeTalkative(aSilentClock));
  return 0;
}
</pre>
<p>and its output:</p>
<pre class="screen">
woof woof
cuckoo cuckoo
woof woof
cuckoo cuckoo
bing bong bing bong
tick tock
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
