37. Increment a Counter

#include <iostream>
using namespace std;

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

    DeviceCounter& operator++() { // prefix ++
        ++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;
}

Solution Details

  • The operator ++ is overloaded as a prefix operator (++counter).
     
  • It increments count and returns the object itself (by reference).
     
  • The loop calls ++counter repeatedly, simulating multiple increments.

     

👉 In simple words:
 Normally ++ works for integers. Here we “teach” C++ how to apply ++ to a custom object, so ++counter means “increment the device count.”

Significance for Embedded Developers

  • In firmware, counters are everywhere: interrupt counts, packet counts, error counters.
     
  • Overloading ++ makes such counters behave naturally, improving readability in low-level code.

     
Loading...

Input

3

Expected Output

Final count=3