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:
    // Declare Buffer first
    Buffer buff;
    // Declare RegisterBlock second
    RegisterBlock regblock;

public:
    // Constructor must store input values
    // Print "Driver initialized"
    Driver(int a, int b){
        buff.write(a);
        regblock.write(b);
        cout << "Driver initialized"<<endl;
    }

    void print() const {
        // Print buffer value
        cout << "Buffer value: "<<buff.read()<<endl;

        // Print register value
        cout<< "Register value: "<<regblock.read()<<endl;
    }

    // Destructor must print "Driver destroyed"
    ~Driver(){
        cout<<"Driver destroyed"<<endl;
    }
};

int main() {
    int a, b;
    cin >> a >> b;

    {
        Driver drv(a, b);
        drv.print();
    }

    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