96. Driver Owns Buffer

#include <iostream>
using namespace std;

class Buffer {
private:
    int data;

public:
    Buffer() {
        cout << "Buffer created" << endl;
    }

    ~Buffer() {
        cout << "Buffer destroyed" << endl;
    }

    void write(int value) {
        data = value;
    }

    int read() const {
        return data;
    }
};

class Driver {
private:
    Buffer buf;

public:
    Driver(int value) {
        buf.write(value);
        cout << "Driver initialized" << endl;
    }

    void print() const {
        cout << "Stored value: " << buf.read() << endl;
    }

    ~Driver() {
        cout << "Driver destroyed" << endl;
    }
};

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

    {
        Driver drv(value);
        drv.print();
    }

    return 0;
}

Explanation & Logic Summary:

The Driver owns the Buffer through composition. When the Driver object goes out of scope, its destructor runs first, followed by destruction of its member objects. This demonstrates deterministic teardown order, which is critical in embedded systems.

Firmware Relevance & Real-World Context:

Embedded drivers frequently manage internal buffers, hardware state, or DMA descriptors. Composition ensures strict ownership and predictable cleanup without dynamic memory or manual resource management, aligning with real-world firmware design principles.

 

 

 

 

Loading...

Input

10

Expected Output

Buffer created Driver initialized Stored value: 10 Driver destroyed Buffer destroyed