I have created this simple object in C++:
class Array
{
int Size;
int * pArr;
public:
explicit Array(int InSize = 0)
{
Size=InSize;
if (Size)
pArr = new int[Size];
else
pArr = NULL;
}
Array(const Array & InArray)
{
Size=InArray.Size;
if (Size)
pArr=new int[Size];
else
pArr=NULL;
}
~Array()
{
if (pArr)
{
delete []pArr;
Size=0;
}
}
};
I am trying to overload the + operator in the following manner:
Array operator+(const Array &LOpArray,const Array &ROpArray)
{
int MinSize=LOpArray.Size<ROpArray.Size ? LOpArray.Size : ROpArray.Size ;
Array ResArray;
if (LOpArray.Size<ROpArray.Size)
ResArray=ROpArray;
else
ResArray=LOpArray;
for (int i=0;i<MinSize;i++)
ResArray.pArr[i]=LOpArray.pArr[i]+ROpArray.pArr[i];
return(ResArray);
}
Assignment is defined as:
Array& Array::operator=(const Array &ROpArray)
{
if (pArr!=ROpArray.pArr)
{
Size=ROpArray.Size;
pArr=new int[Size];
for (int i=0;i<Size;i++)
pArr[i]=ROpArray.pArr[i];
}
return (*this);
}
The problem is when I use it like :
Array A1(20),A2(8),A4;
....//initializing pointer contents
A4=A1+A2;
then A4 has correct values (i.e. size=20 and new,non NULL, int pointer) but all the pointed values have garbage values. debugging showed that in the operator+ function values are actually correct but they are deleted when returning from the operator+ function
What am I doing wrong?