125. Abstract Operation

#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.

  • Abstract classes define interfaces, not implementations.
  • SquareOp and CubeOp provide concrete implementations of apply().
  • A base class pointer (Operation*) is used to achieve runtime polymorphism, allowing the correct function to be selected at runtime.
  • Dynamic memory is safely released using delete.

Firmware Relevance & Real-World Context:

In embedded systems, abstract base classes are commonly used to define hardware-independent interfaces.

Example:

  • A SensorDriver interface may define readValue()
  • AdcSensor or I2cSensor implement the actual hardware logic

This design allows firmware to remain modular, testable, and portable across different hardware platforms.

 



 

Loading...

Input

5 square

Expected Output

25