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

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. Commented Jul 26, 2011 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). Commented Aug 14, 2012 at 8:51

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

There, you can vote to close as a duplicate now.
4

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

Comments

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.

7 Comments

It's worth noting that you can do abstract classes in Java too. :-)
So that what i said. A class with virtual methods = abstract class or?
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.
@JeffPaquette "where all it's methods are pure virtual." except the destructor, it doesn't need to be pure and certainly must be implemented.</nitpick>
@curiousguy if the destructor isn't pure virtual, it's not an exactly interface because it provides implementation /nitpick-pick
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.