CArray a2(a1);
If you are using the default copy constructor, copy only the member variables
a2.ptr = a1.ptr shallow copy garbage is
= An assignment should override shallow copy deep copy
#include<iostream> using namespace std; class CArray { int size; // number of array elements int * PTR; // points to a dynamically allocated array public : CArray-( int S = 0 ); // S representative of the number of array elements CArray-(& CArray-A); // Copy constructor ~ CArray-(); void push_back ( int v); // for adding one end of the array element v & CArray- operator = ( const CArray-a &); // for assignment between an array of objects int length() { return size; } int & CArray::operator[](int i) { return ptr[i]; } }; CArray::CArray(int s) :size(s) { if (s == 0) ptr = NULL; else ptr = new int[s]; } CArray::CArray(CArray & a) { if (!a.ptr) { ptr = NULL; size = 0; return; } ptr = new int[a.size]; memcpy(ptr, a.ptr, sizeof(int) * a.size); size = a.size; } CArray :: ~ CArray () { if (ptr) delete[] ptr; } CArray& CArray::operator= (const CArray& a) { IF (PTR == a.ptr) return * the this ; IF (a.ptr == NULL) // if there is a empty array { IF (PTR) Delete [] PTR; ptr = NULL; size = 0; return *this; } IF (size <a.size) // if the original space is large enough, would not allocate new space { IF (PTR) Delete [] PTR; ptr = new int[a.size]; } memcpy(ptr, a.ptr, sizeof(int)*a.size); size = a.size; return *this; } // CArray & CArray::operator=(const CArray & a) void CArray::push_back(int v) { // add an element to the end of the array IF (PTR) { int * = tmpPtr new new int [size + . 1 ]; // reallocate space the memcpy (tmpPtr, PTR, the sizeof ( int ) * size); // copy of the original contents of the array Delete [] PTR; ptr = tmpPtr; } else ptr = new int[1]; PTR [size ++] = V; // Add a new array element } int main () // To write the variable-length integer array type, so that it can be used as follows: { CArray to; for (int i = 0; i < 5; ++i) a.push_back(i); CArray a2, a3; a2 = a; for (int i = 0; i < a.length(); ++i) cout << a2[i] << " "; a2 = a3; for (int i = 0; i < a2.length(); ++i) cout << a2[i] << " "; cout << endl; a[3] = 100; CArray a4 (a); for (int i = 0; i < a4.length(); ++i) cout << a4[i] << " "; while (1); return 0; }