need help with destructor(im a noob)
#include<stdio.h>
class q1 {
int id;
public:
q1() { id = 1; printf("mkdef: %d\n", id); }
q1(int start) { id = start + 1;
printf("mknew: %d\n", id); }
~q1() { printf("rm: %d\n", id); }
int something(int n) { printf("La-de-da:%d\n", id);
return n*(id+3);}
};
void foo(void)
{
q1 one(1);
one.something(4);
}
int main()
{
q1 a;
printf("%d\n", a.something(3));
foo();
q1 b(6);
printf("Bye..Bye...");
return 0;
}
here is the output log:
mkdef: 1
La-de-da:1
12
mknew: 2
La-de-da:2
rm: 2
mknew: 7
Bye..Bye...rm: 7
rm: 1
Hello.,
im doing this walkthrough and i understand everything except the last part when the destructor gets called last, and rm=1., And at what point are we going out of scope? when we return 0, or with printf statement "bye bye"? when we created a new class q1 b(6), and passed 6 to the function q1(int start){id=start + 1;.....}, so isnt rm should be 7? why it 1 when i compile????? Greatly appreciated
atman
Junior Poster in Training
50 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
//create object called a
mkdef: 1
La-de-da:1
12
//create object called one
mknew: 2
La-de-da:2
//destroy object called two when closing } in foo() found
rm: 2
//create object called b
mknew: 7
Bye..Bye...
//find closing } for main() so destroy objects still in scope
//object b destroyed first since it is on top of stack of object variables, or at least that's how I understand it to work
rm: 7
//then destroy object a
rm: 1
I believe going out of scope occurs with closing brace creating the scope or with completion of loop if that's the definition of the scope.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396