#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:
This guarantees complete and correct shutdown behavior for all driver types.
Firmware Relevance & Real-World Context:
In embedded firmware systems:
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.
Input
0
Expected Output
SPI driver shutdown Base driver shutdown