Polymorphic Driver Shutdown

#include <iostream>
using namespace std;

/**
 * Base Driver class.
 * The 'virtual' keyword on the destructor ensures that when a derived
 * object is deleted via a Driver pointer, the derived destructor is 
 * called first, followed by the base destructor.
 */
class Driver {
public:
    virtual ~Driver() {
        cout << "Base driver shutdown" << endl;
    }
};

/**
 * SpiDriver inherits from Driver.
 */
class SpiDriver : public Driver {
public:
    // Overrides the base destructor behavior
    ~SpiDriver() {
        cout << "SPI driver shutdown" << endl;
    }
};

/**
 * I2cDriver inherits from Driver.
 */
class I2cDriver : public Driver {
public:
    // Overrides the base destructor behavior
    ~I2cDriver() {
        cout << "I2C driver shutdown" << endl;
    }
};

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

    Driver* driver = nullptr;

    // Polymorphic instantiation
    if (value == 0) {
        driver = new SpiDriver();
    } else {
        driver = new I2cDriver();
    }

    // Because ~Driver() is virtual, this will call the derived
    // destructor first, then the base destructor.
    delete driver;

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Expected Output

SPI driver shutdown Base driver shutdown