113. Multiple Inheritance Ambiguity

#include <iostream>
using namespace std;

class PowerControl {
public:
    void enable() {
        cout << "Power enabled" << endl;
    }
};

class InterruptControl {
public:
    void enable() {
        cout << "Interrupt enabled" << endl;
    }
};

// Multiple inheritance
class SpiDriver : public PowerControl, public InterruptControl {
};

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

    SpiDriver spi;

    if (mode == 0) {
        spi.PowerControl::enable();     // Explicitly select PowerControl
    } else if (mode == 1) {
        spi.InterruptControl::enable(); // Explicitly select InterruptControl
    }

    return 0;
}

Explanation & Logic Summary:

When a class inherits from multiple base classes that contain functions with the same name, calling that function through the derived class is ambiguous.

C++ requires explicit qualification using the scope resolution operator (::) to specify which base class function should be invoked.

By qualifying the function call with the base class name, the ambiguity is resolved at compile time without altering the class hierarchy.

Firmware Relevance & Real-World Context:

In embedded firmware systems:

  • Drivers often combine multiple capabilities such as power control, interrupts, DMA, or logging
  • Multiple inheritance is sometimes used to model these capabilities
  • Name collisions across capability interfaces are common

Understanding how to resolve multiple inheritance ambiguity:

  • Prevents build-time errors
  • Avoids unintended behavior
  • Is essential before tackling more complex inheritance patterns such as diamond inheritance

This skill is critical for maintaining safe, readable, and correct embedded C++ firmware code.

 

 

 

 

Loading...

Input

0

Expected Output

Power enabled