5. Protected Access

#include <iostream>
using namespace std;

class BaseDevice {
protected:
    int id;
};

class DerivedDevice : public BaseDevice {
public:
    void setId(int v) { id = v; }
    void printId() { cout << "Device ID: " << id; }
};

int main() {
    DerivedDevice d;
    d.setId(101);
    d.printId();
    return 0;
}

Solution Explanation

  • id is protected, so it’s not accessible in main().
  • The derived class can see it and provide access functions.
     

Layman’s Terms

It’s like a toolbox drawer locked to the outside but always open for your apprentices (derived classes).

Significance for Embedded Developers

Protected is often used in base drivers — shared data accessible to specialized drivers, but not exposed to application code.

Loading...

Input

Expected Output

Device ID: 101