So my problem is this…when I am trying to allocate memory to a pointer, it fails.
This is my MatrixClass definition..
class MatrixClass
{
public:
MatrixClass(int m, int n);
MatrixClass(void);
virtual ~MatrixClass(void);
double getRead(int num1, int num2) const;
double& getReadWrite(int num3, int num4);
void set(int i,int j,double value);//set value at i,j to value
MatrixClass(const MatrixClass &rhs);
void assign(int M,int N);
MatrixClass sum1(const MatrixClass& rhs) const;
MatrixClass operator+(const MatrixClass& rhs);//overloading the + operator
MatrixClass operator-();
private:
double* dataptr;
int M;
int N;
};
I am trying to do this..
MatrixClass BB;
BB = A + B;
So here is my overloaded + function..
MatrixClass MatrixClass::operator +(const MatrixClass &rhs)
{
MatrixClass temp;
//temp.M = this->M + rhs.M;
//temp.N = this->N + rhs.N;
for(int i = 0;i < M;i++)
{
for(int j = 0; j<N;j++)
{
temp.dataptr[i * N + j] = this->getReadWrite(i,j) + rhs.dataptr[i*N+j];
}
}
return temp;
}//end operator +
Once temp returns…it calls the copy constructor…passing temp as ‘rhs’ and ‘this’ would refer to ‘BB’? (Am I right in thinking this?)
MatrixClass::MatrixClass(const MatrixClass &rhs)//copy constructor
{
this->M = rhs.M;
this->N = rhs.N;
dataptr = 0;
if(rhs.dataptr != 0)
{
dataptr = new double[M * N];//allocate memory for the new object being assigned to...
// the line here where I try to allocate memory gives me an error.....Am I right in
//thinking that this would be assigning memory to dataptr of 'BB'?? Values are assigned to //'M' and 'N' fine....
int num = sizeof(double);
memcpy(this->dataptr,rhs.dataptr,M*N*sizeof(double));
}
else
{
this->dataptr = 0;
}
}//end copy constructor
Also the error that i get is this… ‘Unhandled exception at 0x75a0b727 in assignment.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x002af924..’
So basically the qestion I am asking is..why the hell is is the line where I am trying to allocate memory to ‘dataptr’ in the copy constructor giving me problems..it only does this when calling the copy constructor from the return value ‘temp’..
Thanks!
Short answer: you have not implemented Rule of Three properly. In C++11, Rule of Five.
Long answer: you have not implemented
operator=. The compiler generated one is not enough for your case.Apart from that my guess is that your default constructor doesn’t allocate memory for
dataptr. If so, then you’re usingdataptrinoperator+without even allocating memory for it. That is the reason why your program crashes. Even if the default constructor allocates memory, the problem is still there as the value ofrhs.Mandrhs.Nmay be different from what you assume in the default constructor (which is, as you said,4and5respectively).So allocate memory for
dataptrinoperator+. Also, before allocation, you’ve to deallocate the memory which it may point to, and you also need to setMandNto the values ofrhs.Mandrhs.Nrespectively.