BufferTracker Destructor Logging

#include <iostream>
using namespace std;

class BufferTracker {
private:
    int count; // Private integer to track processed bytes

public:
    // Constructor: Initializes count to 0
    BufferTracker() : count(0) {}

    // Method to increase the count for each byte processed
    void addByte(int b) {
        count++;
    }

    // Destructor: Automatically called when the object goes out of scope
    ~BufferTracker() {
        cout << "PROCESSED=" << count << endl;
    }
};

int main() {
    int n;
    // Read the number of bytes to process
    if (!(cin >> n)) return 0;

    {
        // Scope block starts: tracker is created
        BufferTracker tracker;

        for (int i = 0; i < n; i++) {
            int x;
            cin >> x;
            tracker.addByte(x);
        }
        // tracker is still alive here; nothing has been printed yet.
    } // Scope block ends: tracker's destructor is called automatically here.

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

5 1 2 3 4 5

Expected Output

PROCESSED=5