I want to create classes where each class is associated with some function. I want to stack these functions in series such that one function runs after another in a user defined order. I am new to C++ so correct me wherever my syntax is wrong.
#include<iostream>
using namespace std;
class Function
{
public:
virtual void setSuccessor(Function *) = 0;
virtual void Start(int value) = 0;
};
class Prime:public Function
{
public:
Prime()
{
successor=NULL;
}
Function *successor;
void setSuccessor(Function *f)
{
//if a successor is not declared then assign successor.
//else if a successor is already defined then set the new function as the successor of the successor.
if (successor == NULL)
successor = f;
else
successor->setSuccessor(f);
}
void Start(int value)
{
//prime function
cout<<"I am Prime Function\n";
//if successor !=null
// call successor
if(successor!=NULL)
successor->Start(value);
}
};
class Even:public Function
{
public:
Even()
{
successor=NULL;
}
Function *successor;
void setSuccessor(Function *f)
{
if (successor == NULL)
successor = f;
else
successor->setSuccessor(f);
}
void Start(int value)
{
//prime function
cout<<"I am Even Function\n";
//if successor !=null
// call successor
if(successor!=NULL)
successor->Start(value);
}
};
class Pipeline
{
public:
Function *function;
void addToPipe(Function* function)
{
if(this->function==NULL)
this->function=function;
else
function->setSuccessor(function);
}
void start(int value)
{
function->Start(value);
}
};
int main()
{
Pipeline pipe;
pipe.addToPipe(new Prime());
pipe.addToPipe(new Even());
pipe.start(5);
}
In this program I have stacked Prime first then Even. I want that my function prime starts then Even starts. Since no other function is added so it should stop after Even. This program has runtime errors. Please help me detect them
Function
objects usingsetSuccesor
instead of adding them to astd::list
in your pipeline?