{"id":1107,"date":"2013-07-05T01:00:00","date_gmt":"2013-07-05T00:00:00","guid":{"rendered":"https:\/\/www.fussylogic.co.uk\/blog\/?p=1107"},"modified":"2015-02-19T20:36:33","modified_gmt":"2015-02-19T20:36:33","slug":"interfaces-in-c","status":"publish","type":"post","link":"https:\/\/www.fussylogic.co.uk\/blog\/?p=1107","title":{"rendered":"Interfaces in C++"},"content":{"rendered":"<p>C++ has no such thing as an interface. It\u00e2\u20ac\u2122s one of the few <em>Java vs C++<\/em> comparisons that I think Java wins. Interfaces are useful. I\u00e2\u20ac\u2122d like to talk about how we can get similar functionality into C++.<\/p>\n<p>First we need to define our terms. Here\u00e2\u20ac\u2122s an abstract base class in C++.<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\">class Shape : public MyObjectLibraryBase {\n  public:\n    Shape() :\n        mID(<span class=\"dv\">0<\/span>) {}\n    virtual ~Shape() {}\n\n  public:\n    virtual <span class=\"dt\">void<\/span> draw(Canvas &amp;) <span class=\"dt\">const<\/span> = <span class=\"dv\">0<\/span>;\n\n  private:\n    <span class=\"dt\">int<\/span> mID;\n};<\/code><\/pre>\n<p>It\u00e2\u20ac\u2122s a base class because it\u00e2\u20ac\u2122s intended to be inherited from: it has virtual member functions. It\u00e2\u20ac\u2122s abstract because at least one of its virtual member functions has been left undefined. In this case <code>draw()<\/code>. I\u00e2\u20ac\u2122ve also assumed it to be part of some larger hierarchy and made Shape itself inherit from <code>MyObjectLibraryBase<\/code>, it doesn\u00e2\u20ac\u2122t matter what for, it only matters that that\u00e2\u20ac\u2122s what we want.<\/p>\n<p>It should be clear why this has to be abstract \u00e2\u20ac\u201c a <code>Shape<\/code> child class should be able to draw itself, but we don\u00e2\u20ac\u2122t know what an instance of <code>Shape<\/code> would draw, it\u00e2\u20ac\u2122s a placeholder in effect. Therefore we give it a <code>draw()<\/code> member that children will have to implement, but that <code>Shape<\/code> itself can\u00e2\u20ac\u2122t. The two key outcomes of this then are:<\/p>\n<ul>\n<li>We <em>cannot<\/em> instantiate an object of type <code>Shape<\/code> \u00e2\u20ac\u201c it would be unable to <code>draw()<\/code> itself.<\/li>\n<li>We <em>can<\/em> have a pointer to a <code>Shape<\/code>, which will actually be a pointer to a child class of <code>Shape<\/code> that does implement the <code>draw()<\/code> member function.<\/li>\n<\/ul>\n<p>Now imagine that <code>Canvas<\/code> is not written by us, but is instead a third party library. It\u00e2\u20ac\u2122s a library that maintains an object stack, and then renders them efficiently. Very quickly, our abstract base class becomes useless. If we\u00e2\u20ac\u2122ve got a <code>Canvas<\/code> and a <code>Shape<\/code> can\u00e2\u20ac\u2122t we just call <code>Shape::draw(Canvas)<\/code>? The answer is that it\u00e2\u20ac\u2122s unlikely that that\u00e2\u20ac\u2122s how a <code>Canvas<\/code> works; it\u00e2\u20ac\u2122s more likely that the <code>Canvas<\/code> has some higher level interface for managing the objects under its control.<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\"><span class=\"dt\">void<\/span> someFunction(<span class=\"dt\">const<\/span> Shape &amp;S) {\n    Canvas C;\n    <span class=\"co\">\/\/ Error, canvas knows nothing about Shape, so can&#39;t possibly<\/span>\n    <span class=\"co\">\/\/ have an addToDrawStack(Shape) implementation.<\/span>\n    C.addToDrawStack(S);\n}<\/code><\/pre>\n<p>The canvas here is maintaining a stack of objects to draw, maybe to maintain a z-ordering. Our shape knows nothing about that stack, it only knows how to draw itself on a <code>Canvas<\/code>, but we aren\u00e2\u20ac\u2122t responsible for calling <code>draw()<\/code>, <code>Canvas<\/code> itself is \u00e2\u20ac\u201c it knows whether the object is on screen or not, it knows the z-order. What do we do then? A bad solution is to inherit from something Canvas does know about:<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\">class Shape : public MyObjectLibraryBase, public Canvas::Drawable {\n  <span class=\"co\">\/\/ ...<\/span><\/code><\/pre>\n<p>Yuck. <a href=\"http:\/\/stackoverflow.com\/questions\/406081\/why-should-i-avoid-multiple-inheritance-in-c\">Multiple inheritance<\/a>. Avoid it (although, if I\u00e2\u20ac\u2122m being fair, provided you only inherit interface-type abstract base classes, you are committing no crime). An impractical solution is to make <code>Canvas<\/code> understand <code>Shape<\/code>. It\u00e2\u20ac\u2122s impractical because you can\u00e2\u20ac\u2122t go modifying library code with application specific information whenever you like. It\u00e2\u20ac\u2122s not library code then.<\/p>\n<p>The solution is, as we\u00e2\u20ac\u2122ll see, an interface.<\/p>\n<p>C++ doesn\u00e2\u20ac\u2122t have an <code>interface<\/code>; but here\u00e2\u20ac\u2122s one from Java:<\/p>\n<pre class=\"sourceCode java\"><code class=\"sourceCode java\"><span class=\"kw\">interface<\/span> Drawable {\n    <span class=\"dt\">void<\/span> <span class=\"fu\">draw<\/span>(Canvas C);\n}\n\n<span class=\"kw\">class<\/span> Shape <span class=\"kw\">implements<\/span> Drawable {\n    <span class=\"co\">\/\/ ...<\/span>\n    <span class=\"dt\">void<\/span> <span class=\"fu\">draw<\/span>(Canvas C);\n}<\/code><\/pre>\n<p>Barring some syntactical differences; an interface is nothing more than a subset of an abstract base class. It is a subset because it meets these additional criteria:<\/p>\n<ul>\n<li>All its members are functions; it has no member variables<\/li>\n<li>All its members are public<\/li>\n<li>All its members are abstract<\/li>\n<\/ul>\n<p>The distinction between an abstract base class and an interface then is semantic more than anything. An interface <em>is<\/em> an abstract base class, but an abstract base class is not (necessarily) an interface. It would be unusual to have an interface hierarchy, whereas it is not unusual to have a class hierarchy.<\/p>\n<p>A lot of articles out on the internet, when you search for \u00e2\u20ac\u0153interface in C++\u00e2\u20ac\u009d get this idea wrong; they talk only about abstraction. That is a different principle, used for defining common properties of a series of objects, and hiding the differences using polymorphism. An interface is exactly that: an <em>interface<\/em> to an object, probably to meet the needs of some other class library. If it helps, you can think of them as adapters: a way of making X fit into Y. The interface definition lets us adapt the abilities we have to fit requirements of otherwise unrelated classes. This is sometimes referred to as a <em>contract<\/em>.<\/p>\n<p>A commonly used interface in Java, for example, is the <code>Runnable<\/code>. It\u00e2\u20ac\u2122s a simple interface:<\/p>\n<pre class=\"sourceCode java\"><code class=\"sourceCode java\"><span class=\"kw\">interface<\/span> Runnable {\n    <span class=\"dt\">void<\/span> <span class=\"fu\">run<\/span>();\n}<\/code><\/pre>\n<p>In Java you might then have a job queue, a thread, a thread job queue, or whatever, defined in some third party library, that accepts a <code>Runnable<\/code> \u00e2\u20ac\u201c you then add <code>extends Runnable<\/code> to your class definition and implement <code>run()<\/code>, and you get to use the simple <em>interface<\/em> to the library routines. I like to think of interface\u00e2\u20ac\u2122s as the object oriented equivalent of callbacks with opaque pointers; only they\u00e2\u20ac\u2122re far more flexible.<\/p>\n<p>Fundamentally, we should think like this:<\/p>\n<ul>\n<li>Inheritance is a noun relationship. If A inherits from B, then A <em>is-a<\/em> B (with B being a noun). e.g.\u00c2\u00a0a <em>Dog<\/em> is an <em>Animal<\/em>.<\/li>\n<li>Interfaces are a verb relationship. If A implements interface B, then A <em>can-do<\/em> B (with B being a verb). e.g.\u00c2\u00a0a <em>Dog<\/em> can <em>Bark<\/em>.<\/li>\n<li>Composition is an ownership relationship. If A contains a B, then A A <em>has-a<\/em> B. e.g.\u00c2\u00a0a <em>Dog<\/em> has a <em>Leg<\/em>.<\/li>\n<\/ul>\n<p>It\u00e2\u20ac\u2122s no coincidence that object methods are also a verb relationship; since an interface is a way of accessing those verbs.<\/p>\n<p>How can we emulate interfaces in C++ then? The answer in C++ is almost always: another class.<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\"><span class=\"co\">\/\/ Interface.  No member variables, all public, all abstract.<\/span>\n<span class=\"co\">\/\/ This would almost certainly be part of the Canvas library<\/span>\nclass DrawableInterface {\n  public:\n    virtual <span class=\"dt\">void<\/span> draw(Canvas &amp;) <span class=\"dt\">const<\/span> = <span class=\"dv\">0<\/span>;\n};\n\n<span class=\"co\">\/\/ Our Shape definition, on object that we want to make drawable using<\/span>\n<span class=\"co\">\/\/ the third-party Canvas.<\/span>\nclass Shape {\n  public:\n    Shape() : mDrawable(*this) {}\n    <span class=\"co\">\/\/ Users of shape need this to be able to talk to Canvas<\/span>\n    DrawableInterface &amp;dI() { <span class=\"kw\">return<\/span> mDrawable; }\n\n  protected:\n    <span class=\"co\">\/\/ We don&#39;t expect anyone but DrawableShape to be calling draw(), so<\/span>\n    <span class=\"co\">\/\/ this should not be public<\/span>\n    virtual <span class=\"dt\">void<\/span> draw(Canvas &amp;C) <span class=\"dt\">const<\/span> = <span class=\"dv\">0<\/span>;\n\n  private:\n    <span class=\"co\">\/\/ This can be private because our child classes need never know<\/span>\n    <span class=\"co\">\/\/ about it, and they will all implement the Shape abstract methods<\/span>\n    <span class=\"co\">\/\/ that we&#39;re relying on.<\/span>\n    class DrawableShape : public DrawableInterface {\n      public:\n        <span class=\"co\">\/\/ Note when we inherit from an interface class, it&#39;s pretty<\/span>\n        <span class=\"co\">\/\/ much guaranteed that we will be making it concrete and be<\/span>\n        <span class=\"co\">\/\/ adding data members; that&#39;s because we&#39;re _implementing_ the<\/span>\n        <span class=\"co\">\/\/ interface, not creating a new one.<\/span>\n        DrawableShape(Shape&amp; S) : mShape(S) {}\n        <span class=\"co\">\/\/ Our primary job is to redirect a DrawableInterface::draw()<\/span>\n        <span class=\"co\">\/\/ call to a Shape::draw() call.<\/span>\n        <span class=\"dt\">void<\/span> draw( Canvas &amp;C ) <span class=\"dt\">const<\/span> { mShape.draw(C); }\n        Shape mShape;\n    } &amp;mDrawable;\n};<\/code><\/pre>\n<p>It\u00e2\u20ac\u2122s certainly not as pretty as the Java equivalent, but it\u00e2\u20ac\u2122s got the job done. Our main base class <code>Shape<\/code> is now drawable without having to inherit anything from the <code>Canvas<\/code> library \u00e2\u20ac\u201c the inheriting is done in our interface class, <code>DrawableShape<\/code>. The only concession we have to make is that when we pass our <code>Shape<\/code> to the <code>Canvas<\/code> library, we actually pass the return result of <code>dI()<\/code> rather than a <code>Shape<\/code> itself.<\/p>\n<p>It should now be clear that we can \u00e2\u20ac\u0153inherit\u00e2\u20ac\u009d as many interfaces as we wish by adding more functions like <code>dI()<\/code> and their supporting interface classes. You can imagine we could give our shape a <code>Printable<\/code> interface, or a <code>Renderable<\/code> interface \u00e2\u20ac\u201c all making our <code>Shape<\/code> compatible with various different libraries and all without them having to know anything about <code>Shape<\/code>.<\/p>\n<hr \/>\n<p>Let me finish off with a complete example that I\u00e2\u20ac\u2122ve <a href=\"http:\/\/joshldavis.com\/2013\/07\/01\/program-to-an-interface-fool\/\">pinched<\/a> from a Rust implementation, and rewritten in C++ (the original article makes a good case for interfaces). Hopefully seeing it all together will make it clear how to use interfaces in C++.<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\"><span class=\"dt\">int<\/span> main()\n{\n    Log L;\n    Book B;\n\n    <span class=\"co\">\/\/ Call L.makeWarmth() via an interface<\/span>\n    burn(L.burnable());\n    <span class=\"co\">\/\/ Call B.commitCrime() via an interface<\/span>\n    burn(B.burnable());\n\n    <span class=\"kw\">return<\/span> <span class=\"dv\">0<\/span>;\n}<\/code><\/pre>\n<p><code>Log<\/code> and <code>Book<\/code> are not derived from the same base class. <code>burn()<\/code> knows nothing about <code>Log<\/code>s or <code>Book<\/code>s, and yet both can be burnt using it. When viewing the code, pay particular attention to the fact that neither <code>Log<\/code> nor <code>Book<\/code> implement any virtual functions, they do not inherit anything and the function that makes them \u00e2\u20ac\u0153burn\u00e2\u20ac\u009d is named differently in both cases \u00e2\u20ac\u201c those attributes mean that the code that makes these objects usable with the library code has minimal impact on the code we write for our own purposes.<\/p>\n<p>You can find the code in my <code>cpp11<\/code> repository on <a href=\"https:\/\/github.com\/andyparkins\/cpp11\">github<\/a>.<\/p>\n<hr \/>\n<p>As an aside: remember that we can use C++\u00e2\u20ac\u2122s conversion operator overloads to hide all trace that we\u00e2\u20ac\u2122re even doing this; which makes the top-level code even more readable.<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\"><span class=\"dt\">int<\/span> main()\n{\n    Log L;\n    Book B;\n\n    <span class=\"co\">\/\/ Call L.makeWarmth() via an interface<\/span>\n    burn(L);\n    <span class=\"co\">\/\/ Call B.commitCrime() via an interface<\/span>\n    burn(B);\n\n    <span class=\"kw\">return<\/span> <span class=\"dv\">0<\/span>;\n}<\/code><\/pre>\n<p>The C++ compiler will notice that <code>burn()<\/code> requires an <code>IBurnable<\/code> but is being passed something else. It will (before issuing an error) try this instead:<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\">    burn(static_cast&lt;IBurnable&gt;(L));<\/code><\/pre>\n<p>With no changes, this will fail too with a compile error; but if we implement a conversion operator in <code>Log<\/code>, suddenly it will work:<\/p>\n<pre class=\"sourceCode C\"><code class=\"sourceCode c\">class Log\n{\n  public:\n    Log() : iBurnable(*this) {}\n    operator IBurnable &amp;() { <span class=\"kw\">return<\/span> iBurnable; }\n\n  <span class=\"co\">\/\/ ... etc ...<\/span>\n};<\/code><\/pre>\n<p>This is the particular advantage of C++ \u00e2\u20ac\u201c we make intelligent objects that abstract away all the hard work, leaving us with really pleasant high-level interfaces.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ has no such thing as an interface. It\u00e2\u20ac\u2122s one of the few Java vs C++ comparisons that I think Java wins. Interfaces are useful. I\u00e2\u20ac\u2122d like to talk about how we can get similar functionality into C++. First we need to define our terms. Here\u00e2\u20ac\u2122s an abstract base class in C++. class Shape :\u2026 <span class=\"read-more\"><a href=\"https:\/\/www.fussylogic.co.uk\/blog\/?p=1107\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[66,87,79,83,38,6],"_links":{"self":[{"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1107"}],"collection":[{"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1107"}],"version-history":[{"count":8,"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1107\/revisions"}],"predecessor-version":[{"id":1308,"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1107\/revisions\/1308"}],"wp:attachment":[{"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1107"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1107"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.fussylogic.co.uk\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1107"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}