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

  1. Newsgroups: uw.dcs.general,comp.lang.c++
  2. Path: sparky!uunet!pipex!warwick!dcs.warwick.ac.uk!jas
  3. From: jas@dcs.warwick.ac.uk (Jason Morris)
  4. Subject: Operator Overloading problem
  5. Message-ID: <1992Dec16.192756.13271@dcs.warwick.ac.uk>
  6. Sender: news@dcs.warwick.ac.uk (Network News)
  7. Nntp-Posting-Host: snuggle
  8. Organization: Department of Computer Science, Warwick University, England
  9. Date: Wed, 16 Dec 1992 19:27:56 GMT
  10. Lines: 27
  11.  
  12.  
  13.   I have a class, Matrix, and I want to overload the operators +,-,* etc.
  14. Matrix has a private member Data, which is a pointer to some dynamically
  15. allocated storage. Matrix() allocates this storage, and ~Matrix() frees it.
  16. Fine so far.
  17.   Now I want to overload, say, operator+. The problem is that I want to take 
  18. lhs and rhs Matrix arguements, and return the answer in a third Matrix. I
  19. can't pass in a reference to the third Matrix, as operator+ has to take only
  20. two arguements. I can't just pass back a reference to a Matrix declared within
  21. the operator+() function, as it goes out of scope when the function exits.
  22.   So I ended up with:
  23.  
  24.     friend Matrix operator+(Matrix& lhs,Matrix& rhs);
  25.  
  26.   And I just do "return <local Matrix>"
  27.  
  28.   The problem now is that although I'm getting back a copy of the local
  29. variable, not the original (scope is okay), when the operator+ function
  30. returns the destructor is called for the local Matrix, thus deleting the free
  31. store that the data is held in. As my copy has the same value for the pointer
  32. Data, it is now pointing to a useless storage area.
  33.  
  34.   Question is: How should I be doing this? Surely I don't have to use a
  35. function add(Matrix lhs,Matrix rhs,Matrix answer)? That seems to render the
  36. operator overloading pretty useless.
  37.  
  38.     Jas.
  39.