943,910 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 216
  • C++ RSS
Feb 10th, 2009
0

need help with destructor(im a noob)

Expand Post »
C++ Syntax (Toggle Plain Text)
  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
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
atman is offline Offline
50 posts
since Oct 2008
Feb 11th, 2009
0

Re: need help with destructor(im a noob)

//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.
Reputation Points: 718
Solved Threads: 373
Nearly a Posting Maven
Lerner is offline Offline
2,253 posts
since Jul 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Classes and read and print functions
Next Thread in C++ Forum Timeline: problem solving (c-string) urgent





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC