Clock-Dependent Peripheral Design

#include <iostream>
using namespace std;

class ClockController {
public:
    ClockController() {
        cout << "Clock enabled" << endl;
    }

    ~ClockController() {
        cout << "Clock disabled" << endl;
    }

    void write(int offset, int value) {
        cout << "Clocked write: " << offset << " " << value << endl;
    }
};

class Peripheral {
private:
    // Must depend on an existing clock
    ClockController* clk;
public:
    // Must not exist without a clock
    Peripheral(ClockController* clock):clk(clock) {
        cout << "Peripheral ready" << endl;
    }

    ~Peripheral() {
        cout << "Peripheral stopped" << endl;
    }

    void writeReg(int offset, int value) {
        // Must use the clock to perform the write
        clk->write(offset, value);
    }
};

class Driver {
private:
    // Must own the clock
    ClockController clock;
    // Must construct the peripheral using that clock
    Peripheral peripheral;

public:
    Driver():peripheral(&clock) {
        cout << "Driver started" << endl;
    }

    void operate(int offset, int value) {
        // Perform exactly one write
        peripheral.writeReg(offset, value);
    }

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

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

    {
        Driver drv;
        drv.operate(offset, value);
    }

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

8 55

Expected Output

Clock enabled Peripheral ready Driver started Clocked write: 8 55 Driver stopped Peripheral stopped Clock disabled