The term "interface" in C++

Posted by Flexo on Programmers See other posts from Programmers or by Flexo
Published on 2012-02-13T10:14:40Z Indexed on 2013/10/18 22:16 UTC
Read the original article Hit count: 188

Filed under:
|
|
|

Java makes a clear distinction between class and interface. (I believe C# does also, but I have no experience with it). When writing C++ however there is no language enforced distinction between class and interface.

Consequently I've always viewed interface as a workaround for the lack of multiple inheritance in Java. Making such a distinction feels arbitrary and meaningless in C++.

I've always tended to go with the "write things in the most obvious way" approach, so if in C++ I've got what might be called an interface in Java, e.g.:

class Foo {
public:
  virtual void doStuff() = 0;
  ~Foo() = 0;
};

and I then decided that most implementers of Foo wanted to share some common functionality I would probably write:

class Foo {
public:
  virtual void doStuff() = 0;
  ~Foo() {}
protected:
  // If it needs this to do its thing:
  int internalHelperThing(int);
  // Or if it doesn't need the this pointer:
  static int someOtherHelper(int);
};

Which then makes this not an interface in the Java sense anymore.

Instead C++ has two important concepts, related to the same underlying inheritance problem:

  1. virtual inhertiance
  2. Classes with no member variables can occupy no extra space when used as a base

    "Base class subobjects may have zero size"

    Reference

Of those I try to avoid #1 wherever possible - it's rare to encounter a scenario where that genuinely is the "cleanest" design. #2 is however a subtle, but important difference between my understanding of the term "interface" and the C++ language features. As a result of this I currently (almost) never refer to things as "interfaces" in C++ and talk in terms of base classes and their sizes. I would say that in the context of C++ "interface" is a misnomer.

It has come to my attention though that not many people make such a distinction.

  1. Do I stand to lose anything by allowing (e.g. protected) non-virtual functions to exist within an "interface" in C++? (My feeling is the exactly the opposite - a more natural location for shared code)
  2. Is the term "interface" meaningful in C++ - does it imply only pure virtual or would it be fair to call C++ classes with no member variables an interface still?

© Programmers or respective owner

Related posts about c++

Related posts about design