40. Abstract Operation

#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

  • Declaring virtual int apply(int x) const = 0; makes Operation an abstract class.
  • You cannot create an object of Operation directly — it only defines the interface.
  • SquareOp and CubeOp override apply(int) with their specific logic.
  • A Operation* pointer is used for runtime polymorphism: the correct function is chosen at runtime.
     

👉 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

  • Abstract base classes are like driver interfaces in embedded systems.
  • Example: a CommDriver interface might define send() and receive(), while UartDriver or SpiDriver provide actual implementations.
  • This allows firmware to be written against a generic interface, making it modular and hardware-independent.

     
Loading...

Input

5 square

Expected Output

25