dimanche 10 juillet 2016

Using an interface class as member type in another class

I'm trying to design a piece of code that entails the use of an algorithm. The algorithm should be easily replaceable by someone else in the future. So in my LargeClass there has to be a way to invoke a specific algorithm.

I provided some example code below. My idea was to make an interface class IAlgorithm so that you have to provide an implementation yourself. I thought you could initialize it to which ever derived class you wanted in the constructor of the LargeClass. However the below code doesn't compile in VS2015 because IAlgorithm: cannot instantiate abstract class

My question: How should I design this in order to get the result I want?

Thanks in advance!

Algorithm.h

class IAlgorithm
{
protected:
    virtual int Algorithm(int, int) = 0;
};

class algo1 : public IAlgorithm
{
public:
    virtual int Algorithm(int, int);
};

class algo2 : public IAlgorithm
{
public:
    virtual int Algorithm(int, int);
};

Algorithm.cpp

#include "Algorithm.h"

int algo1::Algorithm(const int a, const int b)
{
    // Do something
}

int algo2::Algorithm(const int a, const int b)
{
    // Do something
}

Source.cpp

#include "Algorithm.h"

class LargeClass
{

private:
    IAlgorithm algo;
};

int main()
{


}

Aucun commentaire:

Enregistrer un commentaire