/* 28/02/01 12:55 Kenneth L Moore/Charles McNeil This file shows a shallow copy error: If you compile and execute this file, when you examine the address of the array in object C, you will find that it is the same as the address of B. Therefore, if B gets deleted, C will point to nothing. If you take the comments out from around the overloaded assignment operator and run this file, you will find that C gets its own array. */ #include #include using namespace std; template class Array { size_t len; // size of array public: T *arr; // pointer to actual array Array(): len(5) {arr = new T[len];} Array(int n): len(n) {arr = new T[len];} // used to initialize to len Array(int n, const T& t); // array of len n filled w/t Array(const Array& src); // copy constructor (duh) //~Array() {delete[] arr;} //almighty destructor virtual void print() {cout << "print method error" << endl;} size_t size() const {return len;} T& get(int i); void put(const T& x, int i); void fill(const T& x); T& operator[](int i); }; //---------------------------------------------------------------------- // longer constructors template Array::Array(int n, const T& t): len(n) { arr = new T[len]; for(size_t i = 0; i < len; i++) { arr[i] = t; } } template Array::Array(const Array& src): len(src.len) { arr = new T[len]; for(size_t i = 0; i < len; i++) { arr[i] = src.arr[i]; } } template T& Array::get(int i) { return arr[i]; } template void Array::put(const T& x, int i) { arr[i] = x; } template void Array::fill(const T& x) { for(int i = 0; i < size(); i++) { arr[i] = x; } } //---------------------------------------------------------------------- // el overrido template T& Array::operator[] (int i) { return arr[i]; } //---------------------------------------------------------------------- // build the NumbArray class template class NumbArray : public Array { public: NumbArray(void): Array() {} NumbArray(int n): Array(n) {} NumbArray(int n, T const& t): Array(n, t) {} NumbArray(NumbArray const& src): Array(src) {} void puts(T toPut, int loc){put(toPut, loc);} ~NumbArray(void) {} void print(){ cout << "arr pointer " << arr << endl; for(int i = 0; i < size(); i++) { cout << i << " " << get(i) << endl; } } /* NumbArray& operator=(NumbArray& arg) { if(&arg != this) for(int i = 0; i < size(); ++i) { operator[](i) = arg[i]; } return *this; } */ }; //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { NumbArray A(5,14); NumbArray B(A); NumbArray C; A.print(); B.print(); C = B; B.puts(123,1); C.print(); return 0; }