How to make an interface in C++?

Asked

Viewed 755 times

6

Java, C# and other languages have the concept of interface, which is very useful in some circumstances. How to interface or get closer to it in C++?

1 answer

12


Simply create a 100% abstract class, which is obtained by convention only. Just as there is no keyword to determine that something is an interface, there is nothing that forces the class to be abstract. So just have all methods written without implementation (purely virtual method) and without status:

class Interfaceable {
public:
    virtual void Interface() = 0; // isso é um método puramente virtual
};

If you try to instantiate this class, it does not. It is abstract, there is a method explicitly without implementation.

Then every class that is written with inheritance of this class will be required to implement the method Interface with this signature.

class Classe : public Interfaceable {
public:
    void Interface();
};

void Classe::Interface() {
    cout << "interface";
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

At least there is no other form in standard C++ (has compiler with dialect that allows).

If you want to wear something equivalent to default methods of the Java 8 interfaces, just put an implementation there in the abstract class instead of leaving it as virtual puzzle. Remembering that C++ allows multiple inheritance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.