How can I simulate interfaces in C++?

Tony the Pony picture Tony the Pony · Aug 1, 2009 · Viewed 16.6k times · Source

Since C++ lacks the interface feature of Java and C#, what is the preferred way to simulate interfaces in C++ classes? My guess would be multiple inheritance of abstract classes. What are the implications in terms of memory overhead/performance? Are there any naming conventions for such simulated interfaces, such as SerializableInterface?

Answer

Brian R. Bondy picture Brian R. Bondy · Aug 1, 2009

Since C++ has multiple inheritance unlike C# and Java, yes you can make a series of abstract classes.

As for convention, it is up to you; however, I like to precede the class names with an I.

class IStringNotifier
{
public:
  virtual void sendMessage(std::string &strMessage) = 0;
  virtual ~IStringNotifier() { }
};

The performance is nothing to worry about in terms of comparison between C# and Java. Basically you will just have the overhead of having a lookup table for your functions or a vtable just like any sort of inheritance with virtual methods would have given.