56. Mutable Counter in Const

#include <iostream>
using namespace std;

class AccessTracker {
public:
    AccessTracker() : count(0) {}

    // const function allowed to update internal bookkeeping
    void logAccess() const {
        count++;
    }

    int getCount() const {
        return count;
    }

private:
    mutable int count;  // allows modification inside const functions
};

int main() {
    int n;
    cin >> n;

    const AccessTracker tracker;

    for (int i = 0; i < n; i++) {
        tracker.logAccess();
    }

    cout << tracker.getCount();
    return 0;
}

Explanation & Logic Summary:

  • A const member function promises not to modify the object’s logical external state, such as hardware registers or outputs.
  • Updating internal counters does not break this promise because they do not change externally observable behavior.
  • C++ provides a dedicated mechanism for this purpose: marking member variables as mutable.
  • This preserves const-correctness while allowing safe internal bookkeeping.

Firmware Relevance & Real Embedded Context:

Many embedded drivers update internal counters or cached values inside const functions.

Example:

class TempSensor {
public:
    int readTemperature() const {
        accessCount++;  // allowed: internal bookkeeping
        return i2cReadRegister(TEMP_REG);
    }
private:
    mutable uint32_t accessCount;
};

Common real-world uses:

  • Tracking how many times a sensor register was read
  • Counting interrupts or events
  • Maintaining cached sensor values
  • Updating timestamps inside const driver APIs
  • Profiling and diagnostics
  • Usage tracking for power/performance tuning

Keeping the driver object const is common to prevent accidental modification of hardware settings by application code.

 

 

 

 

Loading...

Input

0

Expected Output

0