115. Runtime Driver Selection

#include <iostream>
using namespace std;

class Driver {
public:
    virtual void start() {
        cout << "Generic driver started" << endl;
    }
};

class SpiDriver : public Driver {
public:
    void start() override {
        cout << "SPI driver started" << endl;
    }
};

class I2cDriver : public Driver {
public:
    void start() override {
        cout << "I2C driver started" << endl;
    }
};

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

    SpiDriver spi;
    I2cDriver i2c;

    Driver* driver = nullptr;

    if (mode == 0) {
        driver = &spi;
    } else {
        driver = &i2c;
    }

    driver->start();   // Correct runtime dispatch

    return 0;
}

Explanation & Logic Summary:

The driver object is accessed exclusively through a base-class pointer.

Without declaring the base-class function as virtual, C++ performs static binding, meaning the function call is resolved based on the pointer type rather than the actual object type.

By declaring Driver::start() as virtual, the compiler enables runtime dispatch.
This ensures the correct derived driver implementation (SpiDriver or I2cDriver) is executed based on the actual object assigned to the base pointer.

Firmware Relevance & Real-World Context:

In real embedded firmware systems:

  • Hardware Abstraction Layers (HAL) often select drivers at runtime based on configuration, board variants, or peripherals detected at startup.
  • Application code interacts only with a base driver interface.
  • Without proper runtime polymorphism, firmware may silently execute incorrect driver logic, leading to hardware malfunction.

This problem reinforces a core Embedded C++ concept required for safe, scalable, and maintainable firmware design.

 

 

 

 

 

Loading...

Input

0

Expected Output

SPI driver started