152. Override Correctness Pitfalls

#include <iostream>
using namespace std;

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

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

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

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

    SpiDriver spi;
    I2cDriver i2c;

    Driver* driver = nullptr;

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

    driver->process();

    return 0;
}

Explanation & Logic Summary:

The base class defines a virtual function process().

  • SPI driver case:
    • The original version used a mismatched signature (const)
    • Without override, the compiler allowed it
    • The base implementation executed silently at runtime
  • I2C driver case:
    • The override keyword was present
    • The incorrect signature caused a compile-time error
    • This prevented a silent runtime bug
  • The fix:
    • Matches the exact base-class signature
    • Adds override to both derived implementations
    • Guarantees compile-time validation and correct polymorphism

Firmware Relevance & Real-World Context:

In real embedded firmware:

  • Drivers override callbacks such as IRQ handlers, DMA completion hooks, and state update functions
  • Silent override failures can cause hardware to remain unconfigured or unresponsive
  • Compile-time detection using override prevents field failures that are extremely difficult to debug

Core rule reinforced:

Every virtual function override must use override, and the compiler must be allowed to validate it.

This discipline is essential for building safe, reliable, and maintainable firmware systems.

 

 

 

 

Loading...

Expected Output

SPI driver processing