I'm trying to work with C++ java/C# like interfaces by creating classes that have only pure virtual methods, like the following: (this is just an example)
class IMyInterface
{
public:
virtual int someFunc() = 0;
virtual ~IMyInterface() {}
};
Everything is fine until I was stuck implementing a method that exchanges two elements in an array of IMyInterface
, since it's not allowed in C++ to instantiate an interface as the compiler will complain about temp
not implementing someFunc()
.
void Exchange(IMyInterface* array, int i, int j)
{
IMyInterface temp = array[i]; // not allowed
array[i] = array[j];
array[j] = temp;
}
so I had to change the interface class definition and get rid of pure virtual function and supply a "default" implementation of the method like so:
class IMyInterface
{
public:
virtual int someFunc()
{
return 0;
}
virtual ~IMyInterface() {}
};
The problem is that IMyInterface
is not an interface anymore, it doesn't force whatever class that will inherit from it to implement someFunc()
.
Anyway around this?