// // Simple class for dynamically-allocated arrays, showing proper // use of copy constructor, destructor, and assignment operator. // All these functions print messages that show what is being // constructed/copied/destructed (specifically, they print // hexadecimal memory locations of their parameters). // #include // has ostream #include // has assert() #include // has copy() class dArray { public: typedef unsigned int length_pos; typedef int item_type; private: item_type * array; length_pos sz; public: // Constructor with size parameter: // Make a dArray with space for n elements. dArray(const int n) { cout << "==== calling constructor, this = " << hex << this << dec << " ====\n"; sz = n; array = new item_type[n]; } // Copy constructor: // Make a copy of all of dv's contents. Be sure to copy dv's array. dArray(const dArray & dv) { cout << "==== calling copy constructor, this = " << hex << this << ", input at " << &dv << dec << " ====\n"; sz = dv.sz; array = new item_type[sz]; // Note this use of the STL copy to copy an array. copy(dv.array, dv.array+sz, array); return; } // Destructor. // Return dynamically-allocated memory to bit bucket. ~dArray(void) { cout << "==== calling destructor, this = " << hex << this << dec << " ====\n"; delete [] array; } // Overloaded assignment operator. // Return dynamically-allocated memory to bit bucket, then make a // copy of dv's contents, as in copy constructor. dArray & operator=(const dArray & dv) { cout << "==== calling assignment operator, this = " << hex<< this << ", input at " << &dv << dec << " ====\n"; if (this != &dv) { // nothing to do if assigning to self sz = dv.sz; delete [] array; array = new item_type[sz]; copy(dv.array, dv.array+sz, array); } return *this; } // A few simple member functions. // Note use of "assert()" to check index and stop the program // rather than try to reference an out-of-bounds array element. // Get size of array. // Post: returns number of elements in array. length_pos size(void) const { return sz; } // Get array element. // Pre: i < number of elements in array. // Post: returns i-th element of array. item_type get(const length_pos i) const { assert(i < sz); return array[i]; } // Set array element. // Pre: i < number of elements in array. // Post: sets i-th element of array to item. void set(const length_pos i, const item_type & item) { assert (i < sz); array[i] = item; return; } };