#include <iostream>
using namespace std;
// Core driver layer
class CoreDriver {
public:
CoreDriver() {
cout << "Core driver initialized" << endl;
}
};
// Communication driver layer
class CommDriver : public CoreDriver {
public:
CommDriver() {
cout << "Comm driver initialized" << endl;
}
};
// SPI device driver layer
class SpiDriver : public CommDriver {
public:
SpiDriver(int s) : speed(s) {
cout << "SPI driver initialized" << endl;
}
void printSpeed() const {
cout << "SPI speed " << speed << endl;
}
private:
int speed;
};
int main() {
int speed;
cin >> speed;
SpiDriver spi(speed);
spi.printSpeed();
return 0;
}
Explanation & Logic Summary
In C++, when an object of a derived class is created:
This order is guaranteed by the C++ language and cannot be changed by the programmer.
In this problem:
CoreDriver initializes shared system resourcesCommDriver performs communication setupSpiDriver applies device-specific configurationThe printed output confirms that initialization occurs in the correct and safe order.
Firmware Relevance & Real-World Context
In real embedded systems:
Multilevel inheritance ensures that lower-level hardware is always initialized before higher-level logic, preventing subtle and difficult-to-debug bring-up failures.
Understanding constructor execution order is essential for writing safe, deterministic embedded C++ firmware.
Input
8
Expected Output
Core driver initialized Comm driver initialized SPI driver initialized SPI speed 8