#include <iostream>
using namespace std;
// Shared base
class DeviceCore {
public:
// This constructor will now only be called once by the most derived class
DeviceCore(int id) : deviceId(id) {
cout << "Device core initialized" << endl;
}
int getId() const {
return deviceId;
}
private:
int deviceId;
};
// Communication layer - use virtual inheritance
class CommLayer : virtual public DeviceCore {
public:
CommLayer(int id) : DeviceCore(id) {}
};
// Power layer - use virtual inheritance
class PowerLayer : virtual public DeviceCore {
public:
PowerLayer(int id) : DeviceCore(id) {}
};
// Diamond inheritance
class SensorDriver : public CommLayer, public PowerLayer {
public:
// Important: In virtual inheritance, SensorDriver must call
// DeviceCore's constructor directly to ensure single initialization.
SensorDriver(int id)
: DeviceCore(id), CommLayer(id), PowerLayer(id) {}
void printId() const {
// getId() is no longer ambiguous because there is only one DeviceCore
cout << "Device ID " << getId() << endl;
}
};
int main() {
int id;
if (!(cin >> id)) return 0;
SensorDriver sensor(id);
sensor.printId();
return 0;
}
Expected Output
Device core initialized Device ID 0