3

Possible Duplicate:
How do you declare an interface in C++?

Somebody asked me a qustion: "In C++ there are no interfaces like in java. But event then you could realize them in c++, how would you do that?"

How? I would make a class with virtual methods. That would be look like an interface as in java or?

Thank you

Community
  • 1
  • 1
Trall
  • 31
  • 1
  • 2
  • Java uses interfaces as a poor man's substitute for multiple inheritance (which is forbidden in Java). C++ fully supports multiple inheritance. It doesn't need Java-style interfaces. – David Hammen Jul 26 '11 at 14:02
  • @close-voters: the alleged duplicate is not. no answer has been given yet of how to do Java-like interface implementation inheritance in C++. which isn't difficult at all, but which is the basic element of any answer to *this* question (and not so for the alleged duplicate). – Cheers and hth. - Alf Aug 14 '12 at 08:51

3 Answers3

9

You can create interfaces in C++ using multiple inheritance.

You create a base class which is pure virtual (all functions =0) and then your classes inherit from this.

Multiple inheritance means you can inherit from as many of these as you like.

// Interface definition
class ISomethingable
{
public:
    virtual ~ISomethingable() {}
    virtual void DoSomething() = 0;    
}

// Your code
class MyClass : public ISomethingable
{
public:
    void DoSomething()
    {
         // Do something concrete.
    }
}

See also: How do you declare an interface in C++?

Community
  • 1
  • 1
xan
  • 7,116
  • 8
  • 41
  • 64
4

Yeah, just make a class with no member variables and pure virtual functions.

Patrick87
  • 25,592
  • 3
  • 33
  • 69
1

An interface in C++ would be an abstract base class -- one that can't be instantiated from. Unlike java interfaces, they can actually have partial implementation and member variables.

Jeff Paquette
  • 6,961
  • 2
  • 28
  • 39
  • 1
    It's worth noting that you can do abstract classes in Java too. :-) – Platinum Azure Jul 26 '11 at 14:09
  • So that what i said. A class with virtual methods = abstract class or? – Trall Jul 26 '11 at 14:15
  • An analog to a java interface would be a C++ class where all it's methods are pure virtual. It would have no implementation, but would dictate a set of functions that must be implemented by some derived class. – Jeff Paquette Jul 26 '11 at 14:22
  • @JeffPaquette "_where all it's methods are pure virtual._" except the destructor, it doesn't need to be pure and certainly must be implemented. – curiousguy Aug 14 '12 at 18:08
  • @curiousguy if the destructor isn't pure virtual, it's not an exactly interface because it provides implementation /nitpick-pick – Jeff Paquette Aug 17 '12 at 22:57
  • @JeffPaquette but even a pure virtual destructor must be implemented! – curiousguy Aug 17 '12 at 23:14
  • @curiousguy Ah yes, you're correct.See http://stackoverflow.com/questions/630950/pure-virtual-destructor-in-c – Jeff Paquette Aug 18 '12 at 14:47