As we all know, some languages have the notion of interfaces. This is Java:
public interface Testable {
void test();
}
How can I achieve this in C++ (or C++11) in most compact way and with little code noise? I’d appreciate a solution that wouldn’t need a separate definition (let the header be sufficient). This is a very simple approach that even I find buggy 😉
class Testable {
public:
virtual void test() = 0;
protected:
Testable();
Testable(const Testable& that);
Testable& operator= (const Testable& that);
virtual ~Testable();
}
This is only the beginning.. and already longer that I’d want. How to improve it? Perhaps there is a base class somewhere in the std namespace made just for this?
What about:
In C++ this makes no implications about copyability of child classes. All this says is that the child must implement
test(which is exactly what you want for an interface). You can’t instantiate this class so you don’t have to worry about any implicit constructors as they can’t ever be called directly as the parent interface type.If you wish to enforce that child classes implement a destructor you can make that pure as well (but you still have to implement it in the interface).
Also note that if you don’t need polymorphic destruction you can choose to make your destructor protected non-virtual instead.