86. Increment a Counter

#include <iostream>
using namespace std;

class DeviceCounter {
private:
    int count;

public:
    DeviceCounter(int c = 0) : count(c) {}

    DeviceCounter& operator++() {
        ++count;
        return *this;
    }

    int getCount() const {
        return count;
    }
};

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

    DeviceCounter counter;

    for (int i = 0; i < n; i++) {
        ++counter;
    }

    cout << "Final count=" << counter.getCount();

    return 0;
}

Explanation & Logic Summary:

  • The prefix increment operator is overloaded using operator++()
  • It increments the internal count variable by 1
  • The operator returns a reference to the current object, which is standard for prefix increment
  • The loop in main() repeatedly applies ++counter, resulting in n total increments

Firmware Relevance & Real-World Context:

Counters are fundamental in firmware development for tracking:

  • Interrupt occurrences
  • Event counts
  • Error or fault frequencies

Overloading the prefix ++ operator allows such counters to behave naturally, improving code readability and maintainability in embedded C++ systems.


 

 

 

 

Loading...

Input

3

Expected Output

Final count=3