/* Value Based Semantics must have 1) default constructor 2) overload of assignment 3) copy constructor 4) destructor Ken Moore Spring 2004 */ #include using namespace std; // class to wrap an array and check for // out of bounds class aWrap{ private: int num; int *a; public: // default constructor aWrap():num(10),a(new int[10]){} /* same as aWrap(){ num = 10; a = new int[10]; } */ // overload constructor aWrap(int n):num(n),a(new int[n]){} // copy constructor aWrap(aWrap &aw){ if(this->a){ delete [] this->a; } this->num = aw.num; this->a = new int[this->num]; for(int i = 0; i < this->num; i++) this->a[i] = aw[i]; } // overload [] operator int & operator[](int i){ if(i>=0&&i<=num) return a[i]; else cout << "OUT OF BOUNDS " << i << endl; return i; } // overload assignment operator = // note this-> is implied and can be totally removed // with no effect on the code. Most programmers never // use this-> unless it is to disambiguate aWrap& operator=(aWrap & aw){ // check for self assignment if(this != &aw){ if(this->a){ delete [] this->a; } // copy into new array this->num = aw.num; this->a = new int[this->num]; for(int i = 0; i < this->num; i++) this->a[i] = aw[i]; } return *this; } // destructor ~aWrap(){ cout << "In d-tor" << endl; delete [] a; } friend ostream& operator << (ostream& o, aWrap &aw); }; ostream& operator << (ostream& o, aWrap &aw){ for(int i = 0; i < aw.num; i++) o << aw[i] << endl; return o; } void main(){ aWrap arr(5); // arr[i] = arr.[](i) for(int i = 0; i < 5; i++){ arr[i] = i + 1; } arr[6]=17; cout << arr << endl; aWrap ar(5); // call assignment operator ar.=(arr) ar = arr; cout << ar << endl; // call copy constructor aWrap x(ar); cout << x << endl; }