logo

UTK Notes


Clicker Questions - 14-Except-Dest

Tell me the ouput of the program below. Put your answer all on one line – if there’s a newline in the program’s output, simply replace it with a space, or even no space. Both will be fine.

So, for example, if the output is:

A
B
C

Then your answer should be “ABC” or “A B C”.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iosteam>
using namespace std;

class Fred {
    public:
        Fred();
        Fred(const Fred &f);
        ~Fred();
};

Fred::Fred() 
{ 
    cout << "A" << endl; 
}

Fred::Fred(const Fred &f) 
{ 
    cout << "B" << endl; 
}

Fred::~Fred() 
{ 
    cout << "C" << endl; 
}

void proc1(Fred f, int i)
{
    cout << "X" << endl;
    if (i != 0) throw (string) "E";
}

void proc2(const Fred &f)
{
    cout << "Y" << endl;
}

int main ()
{
    Fred f;
    Fred *f2;
    
    try {
        proc1(f, 0);
        proc2(f);
        f2 = new Fred;
        proc1(f, 1);
    } catch (const string &s {
        cout << s << endl;
        return 0;
    }

    cout << "F" << endl;
    return 0;
}
Answer
  • The very first thing that happens is the fs constructor is called, because it has been declared inside main(). That prints “A”.
  • Next “proc1(f,0)” is called. That calls the copy constructor for the parameter. It prints “B”.
  • “procl(f,0)” prints “X”.
  • “procl(f,0)” tries the if statement, which is false. It returns, calling the destructor for its parameter: “C”
  • “proc2(f)” is called. It doesn’t call a constructor, its reference parameter. It prints “Y” and returns.
  • “f2 = new Fred” is called. That calls the constructor for “Fred”. It prints “A”
  • “procl(f,l)” is calld. That calls the copy constructor for the parameter It prints “B”.
  • “procl(f,l)” prints “X”.
  • “procl(f, 1)” throws the exception, which makes the procedure return. Before returning it calls the destructor for its parameter f: “C”.
  • The exception is caught in the “catch” statement. That prints “E”.
  • The “catch” statement now returns, which calls the destructor for main’s f. That prints “C”.
  • You’ll note that the destructor for f2 is not called you would have to call “delete” for that.

The answer is “A B X C Y A B X C E C” or “ABXCYABXCEC”.

No Class Stats, PDF Download