helpdesk helpdesk - 1 year ago 82
C++ Question

how to implement Interfaces in C++?

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?

Answer Source

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.

A sample example would be something like this -

class 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
    int myMember;

    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();


    delete f;

    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download