114. Diamond Inheritance Duplication Fix

#include <iostream>
using namespace std;

// Shared base
class DeviceCore {
public:
    DeviceCore(int id) : deviceId(id) {
        cout << "Device core initialized" << endl;
    }

    int getId() const {
        return deviceId;
    }

private:
    int deviceId;
};

// Virtual inheritance
class CommLayer : virtual public DeviceCore {
public:
    CommLayer(int id) : DeviceCore(id) {}
};

class PowerLayer : virtual public DeviceCore {
public:
    PowerLayer(int id) : DeviceCore(id) {}
};

// Single shared DeviceCore
class SensorDriver : public CommLayer, public PowerLayer {
public:
    SensorDriver(int id)
        : DeviceCore(id), CommLayer(id), PowerLayer(id) {}

    void printId() const {
        cout << "Device ID " << getId() << endl;
    }
};

int main() {
    int id;
    cin >> id;

    SensorDriver sensor(id);
    sensor.printId();

    return 0;
}

Explanation & Logic Summary:

In diamond inheritance:

  • Non-virtual inheritance creates multiple base subobjects
  • This duplicates hardware state and runs initialization multiple times

With virtual inheritance:

  • Only one shared base instance exists
  • The most-derived class (SensorDriver) initializes the virtual base
  • Intermediate classes do not create additional copies
  • Hardware state remains consistent and safe

Firmware Relevance & Real-World Context:

In embedded firmware:

  • Base classes often represent hardware registers or peripherals
  • Duplicate initialization can:
    • Reset hardware unintentionally
    • Corrupt configuration
    • Cause undefined behavior

Understanding and fixing diamond inheritance is a critical advanced Embedded C++ skill.

 

 

 

 

Loading...

Input

0

Expected Output

Device core initialized Device ID 0