23. Virtual Public Inheritance

#include <iostream>
using namespace std;

class Device {
public:
    void show() {
        cout << "Generic Device\n";
    }
};

class Sensor : virtual public Device {
    // inherits virtually
};

class Actuator : virtual public Device {
    // inherits virtually
};

class SmartDevice : public Sensor, public Actuator {
public:
    void identify() {
        cout << "Smart Device\n";
    }
};

int main() {
    SmartDevice sd;
    sd.show();      // only one Device instance
    sd.identify();
    return 0;
}

 

Solution Explanation

  • Sensor and Actuator both virtually inherit from Device.
  • This ensures SmartDevice only has one copy of Device.
  • Calling sd.show() works unambiguously.

     

Layman’s Terms

It’s like both sensor and actuator share the same power supply (the base). Without virtual inheritance, you’d accidentally wire two supplies into the same device — causing conflicts.


Significance for Embedded Developers

In firmware, drivers often share a common interface (like Device).

  • Example: A SmartDevice might act as both a sensor and actuator.
  • Virtual inheritance ensures a single consistent interface instead of duplicated base state.

     
Loading...

Input

Expected Output

Generic Device Smart Device