Heap-Free Polymorphic Driver

#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
    // Call startTransfer() polymorphically
    if (mode==0) spi.startTransfer();
    if (mode==1) i2c.startTransfer();

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

0

Expected Output

SPI transfer started