23. Virtual Public Inheritance

Your task is to define the following class hierarchy:

  • Base class: Device
    • A method void show() that prints:
      Generic Device
  • Intermediate classes:
    • Sensor inherits virtual public from Device.
    • Actuator inherits virtual public from Device.
       
  • Derived class: SmartDevice inherits publicly from both Sensor and Actuator.
    • A method void identify() that prints:
      Smart Device
       

The program will:

  1. Create a SmartDevice object.
  2. Call show() (inherited from Device).
  3. Call identify() (defined in SmartDevice).
     

Example

Output:

Generic Device
Smart Device

 

Why this output?

Without virtual inheritance, SmartDevice would have two copies of Device.

By using virtual public, only one shared instance of Device exists.

 

Question Significance

This problem demonstrates how virtual inheritance solves the diamond problem when multiple paths lead to the same base.

Loading...

Input

Expected Output

Generic Device Smart Device