/* Topics with objects * Constructors and Destructors * Why public and private * operator overloading * static, methods and properties * Along the way, more on heap memory */ /* Methods we'll need: * push_back * at or [] * delete * size */ #include using namespace std; // Just stores integers for now class ourvector { size_t isize; size_t allocated_space; // how many integers we have space for int *data; public: ourvector(){ // This is a constructor, note return type is omitted data = new int[10]; isize = 0; allocated_space = 10; } void push_back(int n){ if(isize == allocated_space){ allocated_space *= 2; int *newdata = new int[allocated_space]; for(int i = 0; i < isize; i++) newdata[i] = data[i]; delete [] data; data = newdata; } data[isize] = n; isize++; } int at(size_t idx){ if(idx >= isize) cout << "idx is too large!\n"; return data[idx]; } size_t size(){ return isize; } int& operator[](size_t idx){ if(idx >= isize) cout << "idx is too large!\n"; return data[idx]; } void remove_by_index(size_t idx){ for(int i = idx; i < isize - 1; i++) data[i] = data[i+1]; isize--; } ~ourvector(){ // This is a destructor, runs automatically when object goes out of scope delete [] data; } friend ostream& operator<<(ostream& output_stream, const ourvector& ov); }; ostream& operator<<(ostream& output_stream, const ourvector& ov){ output_stream << "["; for(int i = 0; i < ov.isize; i++) output_stream << ov.data[i] << ", "; output_stream << "\b\b]"; return output_stream; } void test_ourvector(){ /* test routine for our data structure */ ourvector ov; ov.push_back(7); ov.push_back(2); ov.push_back(654); ov.push_back(97); ov[1] = 60000; cout << ov << endl; for(int i = 0; i < 100; i++) ov.push_back(i); ov.remove_by_index(2); for(int i = 0; i < ov.size(); i++) cout << ov[i] << " "; cout << "\n"; } int main(){ test_ourvector(); return 0; }