18. Object Pointer Access

#include <iostream>
using namespace std;

class Sensor {
public:
    int value;
    void printValue() {
        cout << "Sensor Value: " << value << "\n";
    }
};

int main() {
    Sensor s;
    Sensor* ptr = &s;
    ptr->value = 88;
    ptr->printValue();
    return 0;
}

 

Solution Explanation

  • A Sensor object s is declared.
  • A pointer ptr is assigned the address of s.
  • ptr->value = 88; sets the variable through the pointer.
  • ptr->printValue(); calls the method through the pointer.

     

Layman’s Terms

The pointer is like a remote control — it doesn’t hold the object itself, but it lets you operate the object from a distance.

 

Significance for Embedded Developers

Pointers to objects are useful in firmware for:

  • Managing devices dynamically (e.g., an array of device pointers).
  • Passing objects to functions without copying them.
  • Abstracting hardware instances (UART* uart1, UART* uart2).

     
Loading...

Input

Expected Output

Sensor Value: 88