Driver Resource Composition

#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 RegisterBlock {
private:
    int reg;

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

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

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

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

class Driver {
private:
    // Order matters here for construction/destruction requirements
    Buffer buf;
    RegisterBlock regBlock;

public:
    // Constructor handles initialization of resources and prints status
    Driver(int val1, int val2) {
        buf.write(val1);
        regBlock.write(val2);
        cout << "Driver initialized" << endl;
    }

    // Public interface to access private resource data
    void print() const {
        cout << "Buffer value: " << buf.read() << endl;
        cout << "Register value: " << regBlock.read() << endl;
    }

    // Destructor called when Driver goes out of scope
    ~Driver() {
        cout << "Driver destroyed" << endl;
    }
};

int main() {
    int a, b;
    if (!(cin >> a >> b)) return 0;

    {
        // Driver is created here, triggering resource constructors
        Driver drv(a, b);
        drv.print();
    } // drv goes out of scope here, triggering destructors in reverse order

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

10 20

Expected Output

Buffer created RegisterBlock created Driver initialized Buffer value: 10 Register value: 20 Driver destroyed RegisterBlock destroyed Buffer destroyed