Answers.Body: <p>Create an object that creates a new file and writes in to it over several method invocations (not just one). Assure that the object has been deleted before continuing (Make the object go out of scope on the stack or delete a reference and let the reference go out of scope.) You need to assure that he file was closed. The destructor is the proper place to assure that this happens. </p>
  
  <p>To verify that it works correctly, create a different object that reads from the file. If the first object didn't properly close the file this won't be possible. </p>
  
  <p>In some, at least, operating systems you don't even need the second part. The file won't appear in the file system if it was never closed.</p>
  
  <p>The reason for wanting the file written over several invocations of some method(s) is that, if it is just one, an explicit close would be natural in that method. The reason for wanting any references to go out of scope is to assure you that the first object has no effect on the second. </p>
  
  <hr>
  
  <p>Edited for clarification.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:33:14.717Z
Answers.Text: Good. It will also let them see that destructors are not only for memory management. But, don't the file-stream objects of the STL close the file automatically when they go out of scope?
Answers.UserDisplayName: Erel Segal-Halevi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:39:03.180Z
Answers.Text: Yes, if you use such an object, since it has its own destructor. But you can open files otherwise. Any resource held should be released in a destructor if it can't be immediately released. See: http://www.learncpp.com/cpp-tutorial/8-7-destructors/. So your problem (illustrating...) gets harder if everything you use is already properly built. Actually, you can allocate anything for any purpose. Release it in the destructor. Oh. And don't call any destructor twice (implicitly or otherwise). Very bad bug.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T13:20:33.677Z
Answers.Text: @Buffy What OS does not write until close? I know that the file is not **guaranteed** written until you call flush or close. 2nd setting a pointer to null in C++ **WILL NOT** call the destructor; you have to use `delete`. It is not a garbage collected language. Unless you use smart pointers, with the appropriate code.
Answers.UserDisplayName: ctrl-alt-delor
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T13:21:59.537Z
Answers.Text: If STL does this, then what about a class that uses `malloc`/`new`?
Answers.UserDisplayName: ctrl-alt-delor
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T13:26:29.590Z
Answers.Text: @ctrl-alt-delor, I was just describing how to make the object go out of scope, nothing more. I understand that setting to null doesn't invoke the destructor. I don't understand the most recent comment.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T19:26:40.580Z
Answers.Text: Reword of my most resent comment, as @Buffy pointed out that it dose note make sense: If STL does all the file stuff, then how about a class that uses `malloc` or `new` in the constructor, you will need `free` or `delete` in the destructor.
Answers.UserDisplayName: ctrl-alt-delor
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:12:28.340Z
Answers.LastActivityDate: 2018-03-16T20:16:31.430Z
Answers.LastEditDate: 2018-03-16T20:16:31.430Z
Answers.UserDisplayName: Buffy
Answers.Body: <p>There are 2 good examples of patterns where the destuctor is a key.<br>
  This way you can teach a couple of useful patterns on the way.</p>
  
  <p><a href="http://en.cppreference.com/w/cpp/language/raii" rel="nofollow noreferrer">RAII - Resource Acquisition Is Initiation</a>  </p>
  
  <p><a href="http://en.cppreference.com/w/cpp/language/rule_of_three" rel="nofollow noreferrer">Rule of 3/5/0</a></p>
  
  <p>It's easy to give a RAII assignment, just any C style handle that can be released in the end (Like a File handle, windows handle, etc).</p>
  
  <p>If they are more advanced, you can try and teach about shared pointer implementation and have them attempt that (which could get tricky if you want to go into thread safety, etc.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-18T19:05:23.383Z
Answers.Text: Welcome to [cseducators.se]! Those resources might be great, but if you could include, in your answer, what they contain, they would be far more useful
Answers.UserDisplayName: ItamarG3
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-18T18:18:33.167Z
Answers.LastActivityDate: 2018-03-18T18:18:33.167Z
Answers.UserDisplayName: Yochai Timmer
Answers.Body: <p>OK, here is an idea. </p>
  
  <blockquote>
    <p>Write a class Member that keeps track of members in a social network. Each member can follow/unfollow other members and know how many people he/she follows/followed by. Additionally the system keeps track of the number of active members. </p>
  </blockquote>
  
  <p>Here is a sample main program:</p>
  
  <pre><code>Member avi, beni, chana;
  
  void test1() {
      Member dana;
      chana.follow(dana);
      dana.follow(avi);
      cout &lt;&lt; "  " &lt;&lt; chana.numFollowers() &lt;&lt; " " &lt;&lt;  chana.numFollowing() &lt;&lt; endl; // 0 1
      cout &lt;&lt; "  " &lt;&lt; avi.numFollowers() &lt;&lt; " " &lt;&lt;  avi.numFollowing() &lt;&lt; endl; // 1 0
      cout &lt;&lt; "  " &lt;&lt; Member::count() &lt;&lt; endl; // 4
  }
  
  int main() {
      cout &lt;&lt; chana.numFollowers() &lt;&lt; " " &lt;&lt;  chana.numFollowing() &lt;&lt; endl; // 0 0
      test1();
      cout &lt;&lt; chana.numFollowers() &lt;&lt; " " &lt;&lt;  chana.numFollowing() &lt;&lt; endl; // 0 0
      cout &lt;&lt; avi.numFollowers() &lt;&lt; " " &lt;&lt;  avi.numFollowing() &lt;&lt; endl; // 0 0
      cout &lt;&lt; Member::count() &lt;&lt; endl; // 3
  }
  </code></pre>
  
  <p>What do you think?</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-17T19:09:11.733Z
Answers.LastActivityDate: 2018-03-17T19:09:11.733Z
Answers.UserDisplayName: Erel Segal-Halevi
Answers.Body: <p>I'm not a native of C++, but it seems to me that a Conway's Game of Life simulator, with cells as immutable objects, would be a great way to show the need for a destructor.  Without one, your program would quickly run out of memory.</p>
  
  <p>And, of course, it's not a bad approach to the problem.  All you'd have to do to demonstrate why such an approach is reasonable is to first try the naive approach of modifying the active gameboard to figure out the next turn.  This, of course, always leads to incorrect behaviors, since the modification of one cell will be used in the calculation of the next cell.</p>
  
  <p>One final advantage is that you will also be introducing your students to an important and interesting other algorithm in its own right.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:38:55.707Z
Answers.Text: This idea sounds very interesting and fun. I am trying to work out the details.
Answers.UserDisplayName: Erel Segal-Halevi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T13:10:37.553Z
Answers.Text: hmm... on second thought, I think this requires explicit deletion by the programmer, rather than a destructor in the clas..
Answers.UserDisplayName: Erel Segal-Halevi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T18:39:12.780Z
Answers.Text: Releasing the memory occupied by a `Foobar` instance is not the responsibility of the class's destructor.  The destructor gets called _before_ the memory is released.  It's responsibility is to release _other_ resources---to free other objects, to close open files, etc.---that were "owned" by the `Foobar` object.
Answers.UserDisplayName: Solomon Slow
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-11-10T04:03:14.580Z
Answers.Text: I can imagine the simulation being updated with buffers and not needing deletion at all, however, it might be possible to design the class that represents the game board (or a chunk of the board) to free memory in its destructor leaving no need for an explicit delete operation, just an operation to break the game loop and let main() end.
Answers.UserDisplayName: RoboticForest
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:12:13.417Z
Answers.LastActivityDate: 2018-03-16T12:12:13.417Z
Answers.UserDisplayName: Ben I.
Answers.Body: <p>A separate approach entirely from my other answer is to code the main method of a project yourself, but ask your students to build the classes that will make your main method accomplish its task.  This actually opens back up projects like linked lists, as your main will use a slightly different spec than the natural C++ library in any case.</p>
  
  <p>Just include calls to the destructors of the classes when appropriate, and your project will quite naturally require destructors.  And if your project requires any substantial amount of composition, failure to use destructors properly across the project will cause the program to run out of memory.  Thus, you will be modeling the need first by directly calling destructors, and secondarily in a way that causes them to see the need themselves, with the students having to both design and call the relevant destructors for objects held through composition.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:28:05.263Z
Answers.Text: Cute. A bit devious, but cute. Good catch.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:35:54.577Z
Answers.Text: Is it common to call destructors directly in C++?
Answers.UserDisplayName: Erel Segal-Halevi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:39:54.393Z
Answers.Text: @ErelSegal-Halevi You've got me, I could be barking up the wrong tree. I'm a Java guy.  I assumed that they were C++'s way to deallocate objects and that they had to be called, just like constructors.  Upon examining the question now, it seems like I was mistaken about that part.  However, [this](https://stackoverflow.com/questions/16720201/calling-destructor-explicitly) appears to be an interesting case when a destructor should be manually called.  However, it might be out of scope of your course.
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T14:03:28.070Z
Answers.Text: Normally the delete operator on a pointer invokes the destructor. It is rare (very) that destructors are invoked directly.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T19:30:28.787Z
Answers.Text: @Buffy but you suggest that going out of scope, causes the destructor to be called, and that setting pointer to null, causes it to go out of scope. Only calling delete, or being automatic (stack semantics) and going out of scope will cause destructor to run (and object to be freed).
Answers.UserDisplayName: ctrl-alt-delor
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-16T12:22:49.123Z
Answers.LastActivityDate: 2018-03-16T12:29:45.483Z
Answers.LastEditDate: 2018-03-16T12:29:45.483Z
Answers.UserDisplayName: Ben I.
Body: <p>I am teaching destructors in C++ and would like to give the students an interesting homework exercise that requires them to build a class with destructor.</p>
  
  <p>In previous years, the homework were something like "write a linked list, but do not use the classes in the STL". I do not like this - I tell my students that they can use whatever feature of the language that they want, even if we did not learn it in class yet.</p>
  
  <p>The problem is, for every other exercise that I could think of (e.g, tree, graph, etc.) I could easily think of a solution using STL features, that does not require any destructor.</p>
  
  <p>What is an interesting exercise where destructors are really needed?</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-16T18:35:01.167Z
Comments.Text: Google for RAII.
Comments.UserDisplayName: Solomon Slow
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-19T09:46:31.877Z
Comments.Text: Your difficulty is thinking about in-memory *data structures* only.   Chose examples where the objects provide a service, and have something to do when they are "leaving" (sending a shutdown notification  through the network, for example).
Comments.UserDisplayName: Michel Billaud
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-19T09:47:36.767Z
Comments.Text: @MichelBillaud I did not understand. Can you expand?
Comments.UserDisplayName: Erel Segal-Halevi
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-19T11:06:10.250Z
Comments.Text: @ErelSegal-Halevi  I mean, trees, graphs, etc. are merely containers for data, and can be built from basic containers from the standard library. So no surprise you can have RAII managing their destruction. Now a "Logger" object writing to a file. It should write a message when it is closed. Explicitely or by the destructor.
Comments.UserDisplayName: Michel Billaud
Tags: <object-oriented-paradigm><exercises><homework><c++>
Title: A meaningful exercise that requires using a destructor
ThreadText: # A meaningful exercise that requires using a destructor
  
  (Asked by: username_0 on 2018-03-16)
  
  I am teaching destructors in C++ and would like to give the students an interesting homework exercise that requires them to build a class with destructor.
  
  In previous years, the homework were something like "write a linked list, but do not use the classes in the STL". I do not like this - I tell my students that they can use whatever feature of the language that they want, even if we did not learn it in class yet.
  
  The problem is, for every other exercise that I could think of (e.g, tree, graph, etc.) I could easily think of a solution using STL features, that does not require any destructor.
  
  What is an interesting exercise where destructors are really needed?
  
  **Tags:** object-oriented-paradigm, exercises, homework, c++
  
  > **Comments:**
  > **username_1**: Google for RAII.  
  > **username_2**: Your difficulty is thinking about in-memory *data structures* only.   Chose examples where the objects provide a service, and have something to do when they are "leaving" (sending a shutdown notification  through the network, for example).  
  > **username_0**: @username_2 I did not understand. Can you expand?  
  > **username_2**: @username_0  I mean, trees, graphs, etc. are merely containers for data, and can be built from basic containers from the standard library. So no surprise you can have RAII managing their destruction. Now a "Logger" object writing to a file. It should write a message when it is closed. Explicitely or by the destructor.  
  
  ---
  
  ## 5 answers
  
  ### Answer by username_3 on 2018-03-16. Score: 4
  
  Create an object that creates a new file and writes in to it over several method invocations (not just one). Assure that the object has been deleted before continuing (Make the object go out of scope on the stack or delete a reference and let the reference go out of scope.) You need to assure that he file was closed. The destructor is the proper place to assure that this happens.
  
  To verify that it works correctly, create a different object that reads from the file. If the first object didn't properly close the file this won't be possible.
  
  In some, at least, operating systems you don't even need the second part. The file won't appear in the file system if it was never closed.
  
  The reason for wanting the file written over several invocations of some method(s) is that, if it is just one, an explicit close would be natural in that method. The reason for wanting any references to go out of scope is to assure you that the first object has no effect on the second.
  
  ---
  
  Edited for clarification.
  
  > **Comments:**
  > **username_0**: Good. It will also let them see that destructors are not only for memory management. But, don't the file-stream objects of the STL close the file automatically when they go out of scope?  
  > **username_3**: Yes, if you use such an object, since it has its own destructor. But you can open files otherwise. Any resource held should be released in a destructor if it can't be immediately released. See: http://www.learncpp.com/cpp-tutorial/8-7-destructors/. So your problem (illustrating...) gets harder if everything you use is already properly built. Actually, you can allocate anything for any purpose. Release it in the destructor. Oh. And don't call any destructor twice (implicitly or otherwise). Very bad bug.  
  > **username_4**: @username_3 What OS does not write until close? I know that the file is not **guaranteed** written until you call flush or close. 2nd setting a pointer to null in C++ **WILL NOT** call the destructor; you have to use `delete`. It is not a garbage collected language. Unless you use smart pointers, with the appropriate code.  
  > **username_4**: If STL does this, then what about a class that uses `malloc`/`new`?  
  > **username_3**: @username_4, I was just describing how to make the object go out of scope, nothing more. I understand that setting to null doesn't invoke the destructor. I don't understand the most recent comment.  
  > **username_4**: Reword of my most resent comment, as @username_3 pointed out that it dose note make sense: If STL does all the file stuff, then how about a class that uses `malloc` or `new` in the constructor, you will need `free` or `delete` in the destructor.  
  
  ---
  
  ### Answer by username_5 on 2018-03-18. Score: 3
  
  There are 2 good examples of patterns where the destuctor is a key.  
  This way you can teach a couple of useful patterns on the way.
  
  [RAII - Resource Acquisition Is Initiation](http://en.cppreference.com/w/cpp/language/raii)
  
  [Rule of 3/5/0](http://en.cppreference.com/w/cpp/language/rule_of_three)
  
  It's easy to give a RAII assignment, just any C style handle that can be released in the end (Like a File handle, windows handle, etc).
  
  If they are more advanced, you can try and teach about shared pointer implementation and have them attempt that (which could get tricky if you want to go into thread safety, etc.
  
  > **Comments:**
  > **username_6**: Welcome to [cseducators.se]! Those resources might be great, but if you could include, in your answer, what they contain, they would be far more useful  
  
  ---
  
  ### Answer by username_7 on 2018-03-16. Score: 1
  
  I'm not a native of C++, but it seems to me that a Conway's Game of Life simulator, with cells as immutable objects, would be a great way to show the need for a destructor. Without one, your program would quickly run out of memory.
  
  And, of course, it's not a bad approach to the problem. All you'd have to do to demonstrate why such an approach is reasonable is to first try the naive approach of modifying the active gameboard to figure out the next turn. This, of course, always leads to incorrect behaviors, since the modification of one cell will be used in the calculation of the next cell.
  
  One final advantage is that you will also be introducing your students to an important and interesting other algorithm in its own right.
  
  > **Comments:**
  > **username_0**: This idea sounds very interesting and fun. I am trying to work out the details.  
  > **username_0**: hmm... on second thought, I think this requires explicit deletion by the programmer, rather than a destructor in the clas..  
  > **username_1**: Releasing the memory occupied by a `Foobar` instance is not the responsibility of the class's destructor.  The destructor gets called _before_ the memory is released.  It's responsibility is to release _other_ resources---to free other objects, to close open files, etc.---that were "owned" by the `Foobar` object.  
  > **username_8**: I can imagine the simulation being updated with buffers and not needing deletion at all, however, it might be possible to design the class that represents the game board (or a chunk of the board) to free memory in its destructor leaving no need for an explicit delete operation, just an operation to break the game loop and let main() end.  
  
  ---
  
  ### Answer by username_7 on 2018-03-16. Score: 1
  
  A separate approach entirely from my other answer is to code the main method of a project yourself, but ask your students to build the classes that will make your main method accomplish its task. This actually opens back up projects like linked lists, as your main will use a slightly different spec than the natural C++ library in any case.
  
  Just include calls to the destructors of the classes when appropriate, and your project will quite naturally require destructors. And if your project requires any substantial amount of composition, failure to use destructors properly across the project will cause the program to run out of memory. Thus, you will be modeling the need first by directly calling destructors, and secondarily in a way that causes them to see the need themselves, with the students having to both design and call the relevant destructors for objects held through composition.
  
  > **Comments:**
  > **username_3**: Cute. A bit devious, but cute. Good catch.  
  > **username_0**: Is it common to call destructors directly in C++?  
  > **username_7**: @username_0 You've got me, I could be barking up the wrong tree. I'm a Java guy.  I assumed that they were C++'s way to deallocate objects and that they had to be called, just like constructors.  Upon examining the question now, it seems like I was mistaken about that part.  However, [this](https://stackoverflow.com/questions/16720201/calling-destructor-explicitly) appears to be an interesting case when a destructor should be manually called.  However, it might be out of scope of your course.  
  > **username_3**: Normally the delete operator on a pointer invokes the destructor. It is rare (very) that destructors are invoked directly.  
  > **username_4**: @username_3 but you suggest that going out of scope, causes the destructor to be called, and that setting pointer to null, causes it to go out of scope. Only calling delete, or being automatic (stack semantics) and going out of scope will cause destructor to run (and object to be freed).  
  
  ---
  
  ### Answer by username_0 on 2018-03-17. Score: 0
  
  OK, here is an idea.
  
  > Write a class Member that keeps track of members in a social network. Each member can follow/unfollow other members and know how many people he/she follows/followed by. Additionally the system keeps track of the number of active members.
  
  Here is a sample main program:
  
  ```
  Member avi, beni, chana;
  
  void test1() {
      Member dana;
      chana.follow(dana);
      dana.follow(avi);
      cout << "  " << chana.numFollowers() << " " <<  chana.numFollowing() << endl; // 0 1
      cout << "  " << avi.numFollowers() << " " <<  avi.numFollowing() << endl; // 1 0
      cout << "  " << Member::count() << endl; // 4
  }
  
  int main() {
      cout << chana.numFollowers() << " " <<  chana.numFollowing() << endl; // 0 0
      test1();
      cout << chana.numFollowers() << " " <<  chana.numFollowing() << endl; // 0 0
      cout << avi.numFollowers() << " " <<  avi.numFollowing() << endl; // 0 0
      cout << Member::count() << endl; // 3
  }
  
  ```
  
  What do you think?
  
  
  ---
  
  