Possible Duplicate:
Preferred way to simulate interfaces in C++
I was curious to find out if there are interfaces in C++ because in Java, there is the implementation of the design patterns mostly with decoupling the classes via interfaces. Is there a similar way of creating interfaces in C++ then?
If both interfaces have a method of exactly the same name and signature, the implementing class can implement both interface methods with a single concrete method.
No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.
A class implementation of a method takes precedence over a default method. So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.
C# allows the implementation of multiple interfaces with the same method name. To understand how to implement multiple interfaces with the same method name we take an example. In this example, we take two interfaces named as G1 and G2 with the same method name.
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.
An example would be something like this -
class Interface { public: Interface(){} virtual ~Interface(){} virtual void method1() = 0; // "= 0" part makes this method pure virtual, and // also makes this class abstract. virtual void method2() = 0; }; class Concrete : public Interface { private: int myMember; public: Concrete(){} ~Concrete(){} void method1(); void method2(); }; // Provide implementation for the first method void Concrete::method1() { // Your implementation } // Provide implementation for the second method void Concrete::method2() { // Your implementation } int main(void) { Interface *f = new Concrete(); f->method1(); f->method2(); delete f; return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With