#include <iostream>
using namespace std;
/**
* The Bus class represents the shared hardware resource.
* It follows the RAII pattern: starts on construction, stops on destruction.
*/
class Bus {
public:
Bus() {
cout << "Bus ready" << endl;
}
~Bus() {
cout << "Bus stopped" << endl;
}
void write(int addr, int val) {
cout << "Bus write: " << addr << " " << val << endl;
}
};
/**
* The Driver class uses the Bus.
* Instead of inheriting, it holds a reference to a shared Bus object.
*/
class Driver {
private:
Bus& sharedBus; // Reference to the single hardware bus
public:
// Constructor takes a reference to the shared bus
Driver(Bus& bus) : sharedBus(bus) {
cout << "Driver started" << endl;
}
// Uses the shared bus to perform operations
void operate(int addr, int val) {
sharedBus.write(addr, val);
}
~Driver() {
cout << "Driver stopped" << endl;
}
};
int main() {
int a1, v1, a2, v2;
if (!(cin >> a1 >> v1 >> a2 >> v2)) return 0;
// 1. Create exactly ONE Bus object
Bus hardwareBus;
// 2. Use a scope to control the lifetime of the drivers
{
// 3. Create two drivers sharing the same bus reference
Driver d1(hardwareBus);
Driver d2(hardwareBus);
// 4. Perform operations
d1.operate(a1, v1);
d2.operate(a2, v2);
// Drivers go out of scope here, printing "Driver stopped"
}
// Bus goes out of scope here, printing "Bus stopped"
return 0;
}
Input
10 20 30 40
Expected Output
Bus ready Driver started Driver started Bus write: 10 20 Bus write: 30 40 Driver stopped Driver stopped Bus stopped