118. Heap-Free Polymorphic Driver

#include <iostream>
using namespace std;

class Driver {
public:
    virtual void startTransfer() = 0;
    virtual ~Driver() {}
};

class SpiDriver : public Driver {
public:
    void startTransfer() {
        cout << "SPI transfer started" << endl;
    }
};

class I2cDriver : public Driver {
public:
    void startTransfer() {
        cout << "I2C transfer started" << endl;
    }
};

int main() {
    int mode;
    cin >> mode;

    SpiDriver spi;
    I2cDriver i2c;

    Driver& driver = (mode == 0)
                        ? static_cast<Driver&>(spi)
                        : static_cast<Driver&>(i2c);

    driver.startTransfer();

    return 0;
}

Explanation & Logic Summary

  • Both driver objects are created on the stack, ensuring deterministic lifetime.
  • A base-class reference is used to refer to the selected driver at runtime.
  • Virtual dispatch ensures the correct derived implementation executes.
  • No heap allocation is involved, making the design safe for embedded systems.

Firmware Relevance & Real-World Context

In real embedded firmware systems:

  • Heap usage is often forbidden or tightly restricted
  • Drivers are commonly instantiated during system initialization
  • Runtime selection of peripherals is still required

Using stack-allocated objects with polymorphic references provides:

  • Deterministic memory usage
  • Predictable object lifetime
  • Zero heap fragmentation risk

This problem demonstrates a production-grade embedded C++ technique that is essential for firmware running on resource-constrained systems.

 

 

 

 

Loading...

Input

0

Expected Output

SPI transfer started