5. Protected Access

Your task is to define two classes:

  • BaseDevice with a protected variable id (type int).
  • DerivedDevice (inherits from BaseDevice) with:
    • A method setId(int v) to set id.
    • A method printId() to print Device ID: <id>.
       

The program will:

  1. Create a DerivedDevice object.
  2. Call setId(101).
  3. Print Device ID: 101.
     

Example

Output:

Device ID: 101

Why this output?

Because id is protected, it’s not visible to main(), but the derived class can access it.

Question Significance

Shows how protected members can’t be touched outside but are visible in derived classes.

Loading...

Input

Expected Output

Device ID: 101