Path: utzoo!news-server.csri.toronto.edu!rutgers!soleil!mlb.semi.harris.com!trantor.harris-atd.com!jedi!mvm From: mvm@jedi.harris-atd.com (Matt Mahoney) Newsgroups: comp.lang.c++ Subject: Re: Beginners problems (longish) Message-ID: <5829@trantor.harris-atd.com> Date: 14 Mar 91 21:02:14 GMT References: <1991Mar13.170912.4020@cs.UAlberta.CA> Sender: news@trantor.harris-atd.com Reply-To: mvm@jedi.UUCP (Matt Mahoney) Organization: CAE Design Center, Harris Corp., Melbourne, Fl. Lines: 43 In article <1991Mar13.170912.4020@cs.UAlberta.CA> dwelly@saddle-lk.cs.UAlberta.CA (Andrew Dwelly) writes: > >Would someone take pity on me and tell me what I'm doing wrong ??? > >class matrix >{ > float **m; > int rows; > int cols; >public: > > matrix(int,int); > ~matrix(); > float*& operator[](int); > int sizer(); > int sizec(); > friend matrix > operator*(matrix&, matrix&); >}; > code deleted ... The * function has to copy a matrix when it returns, but there is no copy constructor. The default copy constructor just copies the contents, including pointers. The segmentation fault probably occurs when the destructors for the original (inside operator*) and the copy (cout << m * n) delete the same memory. To fix this, add: matrix(const matrix&); // Copy constructor matrix& operator=(const matrix&); // Assignment to your class. Both functions should allocate new memory when they copy their arguments. Also, you may want to change operator* to: friend matrix operator*(const matrix&, const matrix&); so you can pass temporary expressions, as in a * b * c. ----------------------------------------- Matt Mahoney, 407-727-5431, mvm@epg.harris.com #include