#include <iostream>
#include <string>
using namespace std;
class Operation {
public:
virtual int apply(int x) const = 0;
};
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;
}
Explanation & Logic Summary:
Declaring
virtual int apply(int x) const = 0;makes Operation an abstract class.
SquareOp and CubeOp provide concrete implementations of apply().Operation*) is used to achieve runtime polymorphism, allowing the correct function to be selected at runtime.delete.Firmware Relevance & Real-World Context:
In embedded systems, abstract base classes are commonly used to define hardware-independent interfaces.
Example:
SensorDriver interface may define readValue()AdcSensor or I2cSensor implement the actual hardware logicThis design allows firmware to remain modular, testable, and portable across different hardware platforms.
Input
5 square
Expected Output
25