#include <iostream>
using namespace std;
class Driver {
public:
virtual void run() {
cout << "Generic driver running" << endl;
}
};
class SpiDriver : public Driver {
public:
void run() override {
cout << "SPI driver running" << endl;
}
};
class I2cDriver : public Driver {
public:
void run() override {
cout << "I2C driver running" << endl;
}
};
// Fixed: pass by reference to preserve polymorphism
void processDriver(Driver& driver) {
driver.run();
}
int main() {
int mode;
cin >> mode;
SpiDriver spi;
I2cDriver i2c;
if (mode == 0) {
processDriver(spi);
} else {
processDriver(i2c);
}
return 0;
}
Explanation & Logic Summary:
Passing a derived object by value to a function that accepts a base class parameter causes object slicing.
Only the base portion of the object is copied, so the derived behavior is lost.
As a result, the virtual function call resolves to the base implementation instead of the derived one.
By passing the object by reference, the full object is preserved.
This allows the virtual function call to correctly dispatch to the derived driver implementation at runtime.
Firmware Relevance & Real-World Context:
In embedded firmware systems:
Correct embedded C++ designs never pass polymorphic objects by value.
This problem reinforces a critical embedded firmware rule:
Always pass interface objects by reference (or pointer) when runtime polymorphism is required.
Input
0
Expected Output
SPI driver running