throw and catch help!

can someone explain me the steps that was involved to get the output of 4?
X::c was 0 at the beginning and I'm completely lost after that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 #include <iostream>
    #include <exception>
    #include <stdexcept>
    using namespace std;
    
    class E {};
    
    class X {
    public:
        static int c;
        X(int a) { c = a; }
        ~X() { if(c++ > 2) throw new E; }
    };
    
    int X::c = 0;
    
    void f(int i) {
        X* t[2];
        for(int j = 0; j < i; j++)
            t[j] = new X(i+1);
        for(int j = 0; j < i; j++)
            delete t[j];
    }
    
    int main(void) {
        try {
            f(2);
        } catch(...) {
            cout << X::c;
        }
        return 0;
    }
You start with f(2), so i=2. On line 20 when you create X(i+1) you set c=i+1=3 (see line 11). You set that value twice, but that's not a problem. Then you start deleting t[0], so you call the destructor on line 12. It will increase X::c to 4, and throw an error
Topic archived. No new replies allowed.