Reputation: 2619
I need to write a class in C++ that would represent an abstraction of a calculation. That class will have a function that will run an actual calculation.
class Calculation {
Calculation() {}
~Calculation() {}
Calculate(); //member function that runs a calculation
};
I need that class to be able to represent different sorts of calculations and run different calculation as the result of calling Calculation::Calculate()
. What are some good approaches to do this in C++? I could do that just passing some flags into constructor, but this doesn't seem to be a good solution.
Upvotes: 0
Views: 509
Reputation: 363737
How about an object-oriented design?
class Calculation
{
Calculation();
public:
virtual ~Calculation() {}
virtual int Calculate() = 0;
};
class Sum : public Calculation
{
int x, y;
public:
Sum(int x_, int y_) : x(x_), y(y_) {}
~Sum() {}
virtual int Calculate() { return x + y; }
};
Upvotes: 2
Reputation: 45244
You should look into the Command Design Pattern. It is often used to implement "undo" operations in GUI systems but is well suited to other situations where you need to postpone the moment where the actual operation is performed.
C++ implementations typically resort to an abstract class (interface) with a single abstract method with no arguments, then implementing this interface for each operation. The arguments for the computation are bound in the derived class' constructor. Then, instances of your abstract class are queue in some fashion. When it's time to execute the action, just invoke the generic, no-argument method is called.
Upvotes: 0
Reputation: 96281
You can make Calculate
virtual and create child classes that implement the varying behavior you need.
Upvotes: 3