17. Object Accessing Inherited Variables

#include <iostream>
using namespace std;

class Device {
public:
    int id;
};

class Sensor : public Device {
public:
    int value;
};

int main() {
    Sensor s;
    s.id = 101;
    s.value = 75;
    cout << "Device ID: " << s.id << ", Sensor Value: " << s.value;
    return 0;
}

Solution Explanation

  • Sensor inherits from Device, so it automatically has the id variable.
  • The object s can access both s.id and s.value because they are public.
  • Printing them together shows the combined data.
     

Layman’s Terms

It’s like a sensor card that has both a device ID (from the base Device) and a sensor reading (from itself).


Significance for Embedded Developers

In firmware, base classes can hold common identifiers/configurations, while derived classes add specific data.

Example: A Device might store address/id, while a Sensor stores the latest ADC value.

Loading...

Input

Expected Output

Device ID: 101, Sensor Value: 75