#include <iostream>
#include <string>
using namespace std;
/**
* Operation is an abstract base class.
* It defines the interface for mathematical operations.
*/
class Operation {
public:
// Pure virtual function: This makes the class abstract.
// It must be implemented by any non-abstract derived class.
virtual int apply(int x) const = 0;
// Virtual destructor: Essential when deleting derived objects
// through a base class pointer to prevent memory leaks.
virtual ~Operation() {}
};
class SquareOp : public Operation {
public:
// Implementation of the square logic
int apply(int x) const override {
return x * x;
}
};
class CubeOp : public Operation {
public:
// Implementation of the cube logic
int apply(int x) const override {
return x * x * x;
}
};
int main() {
int n;
string opName;
// Read the integer and the operation name
if (!(cin >> n >> opName)) return 0;
Operation* op = nullptr;
// Factory logic: Instantiate the correct derived class based on input
if (opName == "square") {
op = new SquareOp();
} else if (opName == "cube") {
op = new CubeOp();
}
// Execute the operation polymorphically
if (op) {
cout << op->apply(n);
// Clean up dynamic memory
delete op;
}
return 0;
}
Input
5 square
Expected Output
25