#include <iostream>
using namespace std;
/**
* Base Driver Class
* The 'virtual' keyword enables runtime polymorphism, allowing
* the program to decide which function to call at execution time.
*/
class Driver {
public:
// Virtual destructor is vital for base classes to prevent memory leaks
virtual ~Driver() {}
// Marking this virtual allows derived classes to override behavior
virtual void start() {
cout << "Generic driver started" << endl;
}
};
/**
* SPI Implementation
*/
class SpiDriver : public Driver {
public:
// 'override' ensures the signature matches the base class exactly
void start() override {
cout << "SPI driver started" << endl;
}
};
/**
* I2C Implementation
*/
class I2cDriver : public Driver {
public:
void start() override {
cout << "I2C driver started" << endl;
}
};
int main() {
int mode;
if (!(cin >> mode)) return 0; // Basic input safety
// Stack allocation to avoid dynamic memory (as per constraints)
SpiDriver spi;
I2cDriver i2c;
Driver* driver = nullptr;
// Assignment of derived address to base pointer
if (mode == 0) {
driver = &spi;
} else {
driver = &i2c;
}
// Now uses dynamic dispatch to call the correct derived method
if (driver) {
driver->start();
}
return 0;
}
Expected Output
SPI driver started