Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate interfaces in C++?

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?

like image 210
Tony the Pony Avatar asked Aug 01 '09 14:08

Tony the Pony


People also ask

What are interfaces in C?

An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement. An interface may define static methods, which must have an implementation. Beginning with C# 8.0, an interface may define a default implementation for members.

Does C have interface?

C Interfaces and Implementations shows how to create reusable APIs using interface-based design, a language-independent methodology that separates interfaces from their implementations. This methodology is explained by example.

How can we create an interface in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

What is the use of interface with real time example?

An interface in java it has static constants and abstract methods only. for real time example - it is 100% abstraction. example is, Comparator Interface. If a class implements this interface, then it can be used to sort a collection.


1 Answers

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.

like image 142
Brian R. Bondy Avatar answered Oct 06 '22 02:10

Brian R. Bondy