#include <iostream>
using namespace std;
class Driver {
public:
virtual void startTransfer() = 0;
virtual ~Driver() {}
};
class SpiDriver : public Driver {
public:
void startTransfer() {
cout << "SPI transfer started" << endl;
}
};
class I2cDriver : public Driver {
public:
void startTransfer() {
cout << "I2C transfer started" << endl;
}
};
int main() {
int mode;
cin >> mode;
SpiDriver spi;
I2cDriver i2c;
// TODO:
// Select the correct driver WITHOUT using dynamic allocation
Driver* driver;
if ( mode == 0) driver = static_cast<Driver*>(&spi);
if ( mode == 1) driver = static_cast<Driver*>(&i2c);
// Call startTransfer() polymorphically
driver->startTransfer();
return 0;
}
Expected Output
SPI transfer started