109. Reusing Base Initialization

In embedded firmware, multiple peripheral drivers often require the same mandatory initialization steps, such as:

  • Enabling a shared peripheral clock
  • Resetting common control registers

This logic must be written once and reused by multiple derived drivers to avoid duplication and inconsistency.

Your task is to model this design using inheritance.

Step 1: Base Driver

Create a BaseDriver class that:

  • Provides a function named initBase()
  • When called, prints exactly:

    Base driver init start
    Base driver init complete
    

This function represents shared hardware initialization that all drivers must perform.

Step 2: Derived Drivers

Create two derived driver classes:

  • SpiDriver
  • I2cDriver

Each derived class must:

  • Inherit publicly from BaseDriver
  • Provide its own initialization function:
    • initSpi() for SpiDriver
    • initI2c() for I2cDriver
  • Inside its initialization function:
    • Call initBase()
    • Print its own driver-specific message

Required output messages:

SPI driver initialized
I2C driver initialized

Step 3: main()

In main():

  • Read one integer value mode
  • If mode == 0:
    • Create a SpiDriver
    • Call initSpi()
  • If mode == 1:
    • Create an I2cDriver
    • Call initI2c()

This selection simulates choosing different peripherals at runtime while reusing the same base initialization logic.

Input

One integer mode

  • 0 → SPI driver
  • 1 → I2C driver

Program Flow (Mandatory Order)

  1. Read integer mode
  2. Create selected derived driver object
  3. Call derived driver initialization function
  4. Base driver initialization prints
  5. Derived driver-specific initialization prints

 

Example 1

Input:

0

Output:

Base driver init start
Base driver init complete
SPI driver initialized

 

Example 2

Input:

1

Output:

Base driver init start
Base driver init complete
I2C driver initialized

 

Constraints (Strict)

  • Use inheritance only
  • Both derived drivers must inherit publicly from BaseDriver
  • initBase() must be implemented only once in BaseDriver
  • Each derived driver must explicitly call initBase()
  • Do NOT use:
    • Virtual functions
    • Dynamic memory allocation (new, malloc)
    • Composition (no base object as a member)
  • Output text and order must match exactly
  • Use only standard input and output

 

 

 

Loading...

Input

0

Expected Output

Base driver init start Base driver init complete SPI driver initialized