destructor question help!!

The out put of this is :
-------

fatal 1

-------

Object constructed

Object destructed

fatal 2

-------

Object constructed

Object says: hello

Object destructed /////// basically, why is this line after "Object says: hello"

fatal 3

My question is when i=2, the destructor of the class Class is called after the function Hello is called. However, if I look at when i=1, the destructor is called right after. So, I am wondering if destructors are called only at the very end of a function or something like that.
Can someone clarify what is going on. Thanks!

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
 include <iostream>
using namespace std;
class Class {
public:
	Class(void)  { cout << "Object constructed" << endl; }
	~Class(void) { cout << "Object destructed" << endl; }
	void Hello(void) { cout << "Object says: hello" << endl; }
};	
void DoCalculations(int i) {
	if(i == 0) 
		throw string("fatal 1");
	Class object;
	if(i == 1)
		throw string("fatal 2");
	object.Hello();
	if(i == 2)
		throw string("fatal 3");
}
int main(void) {
    for(int i = 0; i < 3; i++) {
	try {
	   cout << "-------" << endl;	
	   DoCalculations(i);
	} catch (string &exc) {
	   cout << exc << endl;
	}
    }	
    return 0;
}
I have another code for example where the initialization of the destructors are confusing me.. I don't know when destructors are called, sometimes they work at the very end of the function, sometimes in the middle.

here is the code;

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
#include <iostream>
using namespace std;
class Class {
public:
	string msg;
	Class(string txt):msg(txt){cout<<"Object [" << msg << "] constructed" << endl; }
	~Class(void) { cout << "Object [" << msg << "] destructed" << endl; }
	void Hello(void) { cout << "Object [" << msg << "] says: hello" << endl; }
};
void DoCalculations(int i) {
	if(i == 0) 
		throw Class("exception 1");
	Class object("object");
	if(i == 1)
		throw Class("exception 2");
	object.Hello();
	if(i == 2)
		throw Class("exception 3");
}
int main(void) {
    for(int i = 0; i < 3; i++) {
	try {
	   cout << "-------" << endl;
	   DoCalculations(i);
	} catch (Class &exc) {
	   cout << "Caught!" << endl;
	   cout << exc.msg << endl;
	}
    }	
    return 0;
}
the destructor is called when the object goes out of scope. The scope is usually { }
Topic archived. No new replies allowed.