I have a general performance question related to some code I am writing.
Consider the following class:
class FuncClass {
public:
FuncClass(unsigned short FunctionCode);
~FeuronClass();
double GetResult();
void Eval(double In1, double In2);
private:
unsigned short FunctionCode;
double Result;
};
FuncClass::FuncClass(unsigned short FunctionCodeIn) {
Result = 0;
FunctionCode = FunctionCodeIn;
}
FuncClass::~FuncClass() {
}
double FuncClass::GetResult() {
return(Result);
}
void FuncClass::Eval(double In1, double In2) {
switch (FunctionCode) {
case 0: // Addition
Result = In1 + In2;
break;
case 1: // Subtraction
Result = In1 - In2;
break;
case 2: // Multiplication
Result = In1 * In2;
break;
default: // Division
if (In2 != 0) {
Result = In1 / In2;
}
} // Imagine there are actually hundreds of different functions like the
four above
}
Every instance of this class is assigned a FunctionCode according to the
function that it needs to perform. The FunctionCode for an instance never
changes for the entire life of the instance. The question I have is whether
a compiler will allocate more memory than necessary for this instance to
accomodate all the functions that the instance _can_ do instead of just
allocating the memory for the one function that it _will_ do. Would it be
more efficient to have many derived classes each with a virtual Eval
function that does only one function so that I would just instantiate the
specific class for the function I want to do? (Really this just means
moving the switch statement out of the class and into the instantiating
code).
Also, would there be any speed benefit in changing my approach, or just a
reduction in memory (or neither) ??