how to implement Interfaces in C++?

C++InterfaceConcept

C++ Problem Overview


> 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?

C++ Solutions


Solution 1 - C++

C++ has no built-in concepts of interfaces. You can implement it using http://en.wikibooks.org/wiki/C++_Programming/Classes/Abstract_Classes">abstract classes which contains only http://en.wikipedia.org/wiki/Virtual_function#Abstract_classes_and_pure_virtual_functions">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;
}

Solution 2 - C++

An "Interface" is equivalent to a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data members. For example:

struct MyInterface
{
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~MyInterface() = 0;
};
MyInterface::~MyInterface () {}

Solution 3 - C++

There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhelpdeskView Question on Stackoverflow
Solution 1 - C++MD Sayem AhmedView Answer on Stackoverflow
Solution 2 - C++iammilindView Answer on Stackoverflow
Solution 3 - C++Alok SaveView Answer on Stackoverflow