I want to have a set of interchangeable classes to perform operations on a dataset. I “think” what I’m trying to do is called Polymorphism but I’m unsure.
This is an example of what I’m trying to do. I want to create an object which contains the initial values, then initialize another class to use the data in the first class and perform a operation using exec, then repeat this with another recursive class.
I want to be able to change the order of operations, the idea is any class can call exec() which will always return unsigned long. init() might be different but is called during initialization and won’t be accessed within a recursive class.
Thanks,
class operationsObject {
public:
virtual unsigned long exec (void) =0;
};
class addObject: public operationsObject {
private:
unsigned long valueA, valueB;
public:
void init(unsigned long a, unsigned long b)
{valueA = a; valueB = b;}
unsigned long exec()
{return valueA + valueB;}
};
class subtractObject: public operationsObject {
private:
operationsObject *obj;
unsigned long valueA;
public:
void init(unsigned long a, operationsObject *o)
{valueA = a; obj = o;}
unsigned long exec()
{return obj->exec() - valueA;}
};
class multiplyObject: public operationsObject {
private:
operationsObject *obj;
unsigned long valueA, valueB;
public:
void init(unsigned long a, unsigned long b, operationsObject *o)
{valueA = a; valueB = b; obj = o;}
unsigned long exec()
{return obj->exec() * valueA * valueB;}
};
int main(){
operationsObject *op1 = new addObject;
operationsObject *op2 = new subtractObject;
operationsObject *op3 = new multiplyObject;
op1->init(4,5);
op2->init(4, op1);
op3->init(1, 2, op2);
unsigned retVal = op3->exec();
}
Your description sounds like you might want to check the following design pattern: Chain of Responsibility.
I’d probably come up with something like this:
exec(non-virtual!) that calls aexecLocalthat implements the behavior you are looking for.Now,
execcould be defined as: