Ahmed Fakhry
Ahmed Fakhry

Reputation: 139

C++ Interfaces Exchanging

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?

Upvotes: 1

Views: 130

Answers (1)

Justin Meiners
Justin Meiners

Reputation: 11113

Interfaces are not fully defined objects so you cannot create instances of them. They are of an undefined size and structure so they obviously cannot be created or used in the value context. You can however create pointers to interfaces (Happy Guys?) because a pointer to an object is very well defined. The sample code could become:

void Exchange(IMyInterface** array, int i, int j)
{
    IMyInterface* temp = array[i]; // allowed :)
    array[i] = array[j];
    array[j] = temp;
}

If the operation is something that should be done by value perhaps a template function would be more appropriate.

Upvotes: 2

Related Questions