need help with destructor(im a noob)

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2008
Posts: 48
Reputation: atman is an unknown quantity at this point 
Solved Threads: 0
atman atman is offline Offline
Light Poster

need help with destructor(im a noob)

 
0
  #1
Feb 10th, 2009
  1. #include<stdio.h>
  2.  
  3. class q1 {
  4. int id;
  5. public:
  6.  
  7. q1() { id = 1; printf("mkdef: %d\n", id); }
  8. q1(int start) { id = start + 1;
  9. printf("mknew: %d\n", id); }
  10. ~q1() { printf("rm: %d\n", id); }
  11. int something(int n) { printf("La-de-da:%d\n", id);
  12. return n*(id+3);}
  13. };
  14.  
  15. void foo(void)
  16. {
  17. q1 one(1);
  18.  
  19. one.something(4);
  20. }
  21.  
  22. int main()
  23. {
  24.  
  25. q1 a;
  26.  
  27. printf("%d\n", a.something(3));
  28. foo();
  29. q1 b(6);
  30. printf("Bye..Bye...");
  31. return 0;
  32. }

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
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,688
Reputation: Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all 
Solved Threads: 265
Lerner Lerner is offline Offline
Posting Virtuoso

Re: need help with destructor(im a noob)

 
0
  #2
Feb 11th, 2009
//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.
Klatu Barada Nikto
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC