Multiple Inheritance Ambiguity

#include <iostream>
using namespace std;

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

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

// SpiDriver inherits from both. 
// Calling spi.enable() would normally cause a "request for member 'enable' is ambiguous" error.
class SpiDriver : public PowerControl, public InterruptControl {
};

int main() {
    int mode;
    if (!(cin >> mode)) return 0; // Read integer mode

    SpiDriver spi;

    // Disambiguate using the Scope Resolution Operator ::
    if (mode == 0) {
        // Explicitly call the version of enable() belonging to PowerControl
        spi.PowerControl::enable();
    } 
    else if (mode == 1) {
        // Explicitly call the version of enable() belonging to InterruptControl
        spi.InterruptControl::enable();
    }

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Expected Output

Power enabled