#include <iostream>
#include <string>
using namespace std;
class Operation {
public:
virtual int apply(int x) const = 0; // pure virtual function
};
class SquareOp : public Operation {
public:
int apply(int x) const override {
return x * x;
}
};
class CubeOp : public Operation {
public:
int apply(int x) const override {
return x * x * x;
}
};
int main() {
int n;
string opName;
cin >> n >> opName;
Operation* op = nullptr;
if (opName == "square") {
op = new SquareOp();
} else if (opName == "cube") {
op = new CubeOp();
}
if (op) {
cout << op->apply(n);
delete op;
}
return 0;
}
Solution Details
👉 In simple words:
The base class Operation is a rulebook: “Every operation must know how to apply itself.” The derived classes (SquareOp, CubeOp) follow that rule and provide the actual calculation.
Significance for Embedded Developers
Input
5 square
Expected Output
25