In Go, if the type has all the methods that the interface defined then it can be assigned to that interface variable without explicitly inheriting from it.
Is it possible to mimic this feature in C/C++?
Yes. You can use a pure abstract class, and use a template class to wrap types "implementing" the abstract class so that they extend the abstract class. Here's a barebones example:
#include <iostream>
// Interface type used in function signatures.
class Iface {
public:
virtual int method() const = 0;
};
// Template wrapper for types implementing Iface
template <typename T>
class IfaceT: public Iface {
public:
explicit IfaceT(T const t):_t(t) {}
virtual int method() const { return _t.method(); }
private:
T const _t;
};
// Type implementing Iface
class Impl {
public:
Impl(int x): _x(x) {}
int method() const { return _x; }
private:
int _x;
};
// Method accepting Iface parameter
void printIface(Iface const &i) {
std::cout << i.method() << std::endl;
}
int main() {
printIface(IfaceT<Impl>(5));
}
I guess some rough equivalence might be feasible with GObject.
Yes, of course.
In fact the code that handles interfaces in the runtime is written in C. http://code.google.com/p/go/source/browse/src/pkg/runtime/iface.c
I took a stab at it for C++. I ended up with something that works, but is a macro circus: https://github.com/wkaras/c-plus-plus-misc/tree/master/IFACE . An interface is two pointers, one to object data members, and another to the equivalent of a virtual table (a structure of pointers to thunk functions that call member functions). These tables are (unfortunately) generated at run-time. Conversion from an interface to a sub-interface requires an unordered_map look up, so it's O(1) time complexity on average. As compared with converting a derived class pointer/reference to one to a base class, which is O(1) worst-case.
It's not very usable, but it does show that interfaces could be (cleanly) added to C++ with relatively little effort. There are cases where interfaces are better than inheritance-based OO, and the cow is well out of the barn as far as trying to keep C++ small.