Override Correctness Pitfalls

#include <iostream>
using namespace std;

/**
 * Base class defining the interface for all drivers.
 */
class Driver {
public:
    // Virtual function to be overridden by hardware-specific drivers
    virtual void process() {
        cout << "Generic driver processing" << endl;
    }
    
    // Virtual destructor is good practice for polymorphic base classes
    virtual ~Driver() {}
};

/**
 * SPI Driver: Fixed the silent override failure.
 * Removed 'const' so the signature matches Driver::process().
 */
class SpiDriver : public Driver {
public:
    void process() override { 
        cout << "SPI driver processing" << endl;
    }
};

/**
 * I2C Driver: Fixed the compile-time mismatch.
 * Removed 'int mode' so the signature matches Driver::process().
 */
class I2cDriver : public Driver {
public:
    void process() override { 
        cout << "I2C driver processing" << endl;
    }
};

int main() {
    int mode;
    if (!(cin >> mode)) return 0;

    SpiDriver spi;
    I2cDriver i2c;

    // Pointer to the base class used to demonstrate polymorphism
    Driver* driver = nullptr;

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

    // This call is resolved at runtime based on the actual object type
    driver->process();

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Expected Output

SPI driver processing