I have to write an intArray class with different operators overloaded for it,
The problem is that how i can overload operator - for it,here is the class code (partial)
in the main i have to use code similar to thisCode:class intArray { int *ptr; int size; public: intArray(int=0); intArray(int*,int=0); intArray& operator=(const intArray&); intArray operator-(intArray&); ~intArray(){delete [] ptr;} void Print()const; }; intArray intArray::intArray(int s=0) { size=s; ptr=new int[size]; } intArray intArray::operator-(intArray& rhs) { intArray temp(size); . //perform operations on temp and rhs original lhs array . . return temp; //causing problem }
and it is the problem ,when operator - is called it returns the temporary arrayCode:int main() { int p[]={2,3}; intArray a1(p,2); intArray a2(2); (a1-a2).Print(); //print result of a1 - a2 return 0; }
but since its scope is only limited to operator - function,
the ~intArray() destructor is called and it frees up the memory which is being used by
"temp"
,so how i can convert it in such a way that function call (a1-a2).Print()
should be valid...
i have tried to do it by removing ~intArray() destructor,it works fine but
what about the dynamic memory allocated by it????



LinkBack URL
About LinkBacks


