Java, C #, and other languages have the interface concept, which is very useful in some circumstances. How to make an interface or the closest to it in C ++?
Java, C #, and other languages have the interface concept, which is very useful in some circumstances. How to make an interface or the closest to it in C ++?
Just create a 100% abstract class, which is only obtained by convention. 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 stateless:
class Interfaceable {
public:
virtual void Interface() = 0; // isso é um método puramente virtual
};
If you try to instantiate this class, you can not. It is abstract, there is a method explicitly without implementation.
Then any class written with inheritance of this class will be required to implement the Interface
method with this signature.
class Classe : public Interfaceable {
public:
void Interface();
};
void Classe::Interface() {
cout << "interface";
}
See working on ideone .
At least there is no other way in standard C ++ (it has compiler with dialect that allows).
If you want to use something equivalent to the default methods of Java 8 interfaces , just put an implementation there in the abstract class rather than leaving it as pure virtual . Remembering that C ++ allows multiple inheritance.