Copy Constructor Failing
Sep 7, 2013 at 12:48am UTC
In my program, I have created an array class.
However, even though I have a deep copy constructor, it only works for the first element of the actual array. Please help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <iostream>
using namespace std;
class INTARR
{
public :
INTARR(int s);
INTARR(INTARR& a);
~INTARR();
int & operator [](int index);
INTARR operator =(INTARR a);
INTARR operator +(INTARR b);
int GetSize() {return (size);}
private :
int * arr;
int size;
};
int main()
{
INTARR c(3);
c[0] = 1;
c[1] = 2;
c[2] = 3;
INTARR d(3);
d = c;
cin.get();
return 0;
}
INTARR::INTARR(int s)
{
arr = new int [s];
size = s;
}
INTARR::INTARR(INTARR& a)
{
arr = new int [a.size];
*arr = *(a.arr);
size = a.size;
}
INTARR::~INTARR()
{
delete [] arr;
}
int & INTARR::operator [](int index)
{
if ((index < size) && ( index >= 0))
return arr[index];
else
return arr[0];
}
INTARR INTARR::operator =(INTARR a)
{
for (int i = 0; i < a.size; i++)
{
(*this )[i] = a[i]; cout << "Size: " << a.size << " New Content: " << (*this )[i] << " Original Content: " << a[i] << endl;
}
return *this ;
}
The output for both [1] and [2] of the arrays come out as some value that was present at that RAM Address.
Thank you.
Last edited on Sep 7, 2013 at 1:27am UTC
Sep 7, 2013 at 1:24am UTC
Remember, arr is a pointer to the first element in the array, so *arr deferences that pointer and gives you the value stored in arr[0], same for *(a.arr).
Here is a modified version of your copy constructor:
1 2 3 4 5 6
INTARR::INTARR(INTARR& a)
{
arr = new int [a.size];
std::copy_n(a.arr, a.size, arr);
size = a.size;
}
Sep 7, 2013 at 1:29am UTC
Oh, right. That makes complete sense now...
Thanks for the help.
Topic archived. No new replies allowed.