🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: uw.dcs.general
Article #1

Operator Overloading problem

#1
From: Jason Morris
Date: Wed, 16 Dec 1992 19:27
27 lines
1751 bytes
  I have a class, Matrix, and I want to overload the operators +,-,* etc.
Matrix has a private member Data, which is a pointer to some dynamically
allocated storage. Matrix() allocates this storage, and ~Matrix() frees it.
Fine so far.
  Now I want to overload, say, operator+. The problem is that I want to take 
lhs and rhs Matrix arguements, and return the answer in a third Matrix. I
can't pass in a reference to the third Matrix, as operator+ has to take only
two arguements. I can't just pass back a reference to a Matrix declared within
the operator+() function, as it goes out of scope when the function exits.
  So I ended up with:

    friend Matrix operator+(Matrix& lhs,Matrix& rhs);

  And I just do "return <local Matrix>"

  The problem now is that although I'm getting back a copy of the local
variable, not the original (scope is okay), when the operator+ function
returns the destructor is called for the local Matrix, thus deleting the free
store that the data is held in. As my copy has the same value for the pointer
Data, it is now pointing to a useless storage area.

  Question is: How should I be doing this? Surely I don't have to use a
function add(Matrix lhs,Matrix rhs,Matrix answer)? That seems to render the
operator overloading pretty useless.

    Jas.
Technical Details
Message-ID: <1992Dec16.192756.13271@dcs.warwick.ac.uk>
Path: arc1-ca.pugleaf.net!sparky!uunet!pipex!warwick!dcs.warwick.ac.uk!jas

Show Full Headers
Complete Article Headers
Newsgroups: uw.dcs.general,comp.lang.c++
Path: arc1-ca.pugleaf.net!sparky!uunet!pipex!warwick!dcs.warwick.ac.uk!jas
From: jas@dcs.warwick.ac.uk (Jason Morris)
Subject: Operator Overloading problem
Message-ID: <1992Dec16.192756.13271@dcs.warwick.ac.uk>
Sender: news@dcs.warwick.ac.uk (Network News)
Nntp-Posting-Host: snuggle
Organization: Department of Computer Science, Warwick University, England
Date: Wed, 16 Dec 1992 19:27:56 GMT
Lines: 27