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:
    // Driver must own the buffer
    Buffer buff;

public:
    // Constructor should accept input value and store it in buffer
    Driver(){
        int x;
        cin >> x;
        buff.write(x);
        cout << "Driver initialized" << endl;
    }

    void print() const {
        // Print stored value
        int y = buff.read();
        cout << "Stored value: " << static_cast<int>(y) << endl;
    }

    // Add destructor to observe shutdown
    ~Driver(){
        cout << "Driver destroyed" <<endl;
    }
};

int main() {

    {
        Driver drv;
        drv.print();
    }

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

10

Expected Output

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