home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / cplus / 18196 < prev    next >
Encoding:
Text File  |  1992-12-21  |  1.4 KB  |  45 lines

  1. Newsgroups: uw.dcs.general,comp.lang.c++
  2. Path: sparky!uunet!microsoft!wingnut!pauljo
  3. From: pauljo@microsoft.com (Paul Johns)
  4. Subject: Re: Operator Overloading problem
  5. Message-ID: <1992Dec17.214050.24924@microsoft.com>
  6. Date: 17 Dec 92 21:40:50 GMT
  7. Organization: Microsoft, Redmond WA USA
  8. References: <1992Dec16.192756.13271@dcs.warwick.ac.uk> 
  9. Lines: 34
  10.  
  11. Any time you have a class which contains a pointer to 
  12. dynamically-allocated memory (as your class does), you
  13. WILL NEED an appropriate:
  14.  
  15.     Assignment operator
  16.     Copy constructor
  17.     Destructor
  18.  
  19. You will likely also need a default constructor.
  20.  
  21. Your symptoms are consistent with forgetting one
  22. or both of the assignment operator or copy constructor,
  23. depending on how the addition operator was used. 
  24. (Forgetting the destructor results in a memory leak.)
  25.  
  26. If you forget any of these, you'll end up with the
  27. kinds of problems you're seeing.
  28.  
  29. Note that these problems can be silent:  since the
  30. compiler provides you with these functions if you
  31. don't provide them, you won't get any sort of
  32. compiler error.
  33.  
  34. What I think is happening in your case is that the
  35. compiler supplied assignment operator or copy 
  36. constructor is just doing a memberwise copy of
  37. your object.  Your addition function is creating
  38. the temporary and allocating memory for it.  The
  39. pointer to this memory is copied from the temporary
  40. to the object to which you're assigning/copying
  41. rather than copying the memory.
  42.  
  43. // Paul Johns
  44.  
  45.