117. Polymorphic Driver Shutdown

#include <iostream>
using namespace std;

class Driver {
public:
    virtual ~Driver() {
        cout << "Base driver shutdown" << endl;
    }
};

class SpiDriver : public Driver {
public:
    ~SpiDriver() {
        cout << "SPI driver shutdown" << endl;
    }
};

class I2cDriver : public Driver {
public:
    ~I2cDriver() {
        cout << "I2C driver shutdown" << endl;
    }
};

int main() {
    int value;
    cin >> value;

    Driver* driver = nullptr;

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

    delete driver;

    return 0;
}

Explanation & Logic Summary:

The program selects a driver implementation at runtime based on input.

The driver object is destroyed using a base-class pointer.

If the base-class destructor is not virtual, only the base destructor executes, and the derived driver’s cleanup logic is skipped.

Declaring the base-class destructor as virtual ensures:

  1. The correct derived destructor executes first
  2. The base destructor executes second

This guarantees complete and correct shutdown behavior for all driver types.

Firmware Relevance & Real-World Context:

In embedded firmware systems:

  • Drivers are often selected at runtime based on configuration
  • Cleanup code may disable peripherals, clocks, or interrupts
  • Incorrect destruction can leave hardware active or misconfigured

This problem reinforces a critical embedded C++ rule:

Any base class intended for polymorphic deletion must declare a virtual destructor.

This is essential for safe, deterministic, and maintainable firmware design.

 

 

 

Loading...

Input

0

Expected Output

SPI driver shutdown Base driver shutdown