-
intArray class problem!
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)
Code:
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
}
in the main i have to use code similar to this
Code:
int main()
{
int p[]={2,3};
intArray a1(p,2);
intArray a2(2);
(a1-a2).Print(); //print result of a1 - a2
return 0;
}
and it is the problem ,when operator - is called it returns the temporary array
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????
-
Hmm I see the problem. Iīm not sure of this but I give it a try. When you are returing a value by value (like in your case) it creates a temporary object to the function that invoked that function (hope you get it). And if your a returing an user-defined object the copy constructor is invoked. In other words I think your problem lies that you donīt have a copy-construtor (donīt realy on default copy-construtor). Create an approriate copy-constructor and tell me if it works.
-
i have written a copy constructor
but it does not seem to work,without it junk values was being printed but with a copy constructor,it does not print anything after return and returning a run time error,here is the copy constructor
Code:
intArray::intArray(intArray& t)
{
size=t.size;
delete [] ptr;
ptr=new int[t.size];
for(int i=0;i<t.size;i++)
{
*(ptr+i)=*(t.ptr+i);
}
}
-
Quote:
Originally posted by nag
Code:
intArray::intArray(intArray& t)
{
size=t.size;
delete [] ptr;
ptr=new int[t.size];
for(int i=0;i<t.size;i++)
{
*(ptr+i)=*(t.ptr+i);
}
}
because you
delete [] ptr
in your example, but ptr is just some garbage value (remember it's an unitialized member, you're in a constructor).