Question: Why might it be better to use polymorphism in Problem (1) instead of the string type member variable and if statements? (Explain in your own

Why might it be better to use polymorphism in Problem (1) instead of the string type member variable and if statements? (Explain in your own words using 3-4 complete sentences)
Problem (1)
You may create any number of classes.
You may edit the main() function.
Remove the variable string type completely from the entire program.
-- Note: Entire program includes all classes, all functions, and main().
Get rid of every if and if else statement completely from the entire program.
-- Note: Entire program includes all classes, all functions, and main().
accumulate(...), min_element(...), and max_element(...) are algorithms from the standard template library referenced with #include .
Hint: Use polymorphism.
Program:
#include
#include
#include
#include
using namespace std;
class ArrayFunction {
public:
ArrayFunction(const string& type) {
this->type = type;
}
float calculate(float array[], int size) {
if (type == "mean") {
float sum = accumulate(array, array + size, 0.0);
return sum / size;
}
else if (type == "min") {
return *min_element(array, array+size);
}
else if (type == "max") {
return *max_element(array, array+size);
}
else if (type == "first") {
return array[0];
}
return 0;
}
private:
string type;
};
int main() {
float array[] {1,2,3,7};
vector functions;
functions.push_back(new ArrayFunction("mean"));
functions.push_back(new ArrayFunction("min"));
functions.push_back(new ArrayFunction("max"));
functions.push_back(new ArrayFunction("first"));
for (int i = 0; i < functions.size(); i++) {
cout << functions[i]->calculate(array, 4) << endl;
delete functions[i];
}
return 0;
}
Example Output:
3.25
1
7
1

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!