112. Multilevel Driver Initialization

#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:

  1. The base class constructor runs first
  2. Then each intermediate base class constructor runs
  3. Finally, the most-derived class constructor executes

This order is guaranteed by the C++ language and cannot be changed by the programmer.

In this problem:

  • CoreDriver initializes shared system resources
  • CommDriver performs communication setup
  • SpiDriver applies device-specific configuration

The printed output confirms that initialization occurs in the correct and safe order.

Firmware Relevance & Real-World Context

In real embedded systems:

  • Core drivers may initialize clocks, power, or memory controllers
  • Communication drivers configure buses like SPI, I²C, or UART
  • Device drivers finalize timing, mode, and speed settings

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.

 

 

 

 

Loading...

Input

8

Expected Output

Core driver initialized Comm driver initialized SPI driver initialized SPI speed 8