#pragma once #include <iostream> const size_t MAX_START_ELEMENTS{10}; template <typename DataT> class ArrayT { public: ArrayT(); ArrayT(const ArrayT & other); ~ArrayT(); ArrayT & operator=(const ArrayT & other); size_t Size() const; size_t Capacity() const; void push_back(const DataT & newData); const DataT & at(size_t index) const; DataT & at(size_t index); const DataT & operator[](size_t index) const; DataT & operator[](size_t index); // this is not needed, it is to show that not all // syntax errors are caught in functions that are not called. // // See code below, it will attempt to cast a DataT to an int. int BadFun(); private: size_t size{0}, capacity{MAX_START_ELEMENTS}; DataT *data{nullptr}; }; template<typename DataT> ArrayT<DataT>::ArrayT() { data = new DataT[capacity]; } template<typename DataT> ArrayT<DataT>::ArrayT(const ArrayT & other) { size = other.size; capacity = other.capacity; if (other.data != nullptr) { data = new DataT[capacity]; for(size_t i = 0; i < size; ++i) { data[i] = other.data[i]; } } else { data = nullptr; } } template<typename DataT> ArrayT<DataT>::~ArrayT() { if (data != nullptr) { delete [] data; } } template<typename DataT> ArrayT<DataT> & ArrayT<DataT>::operator = ( const ArrayT & other) { if (this != &other) { // do a deep copy if (data != nullptr) { delete [] data; } size = other.size; capacity = other.capacity; data = new DataT[capacity]; for(size_t i = 0; i < size; ++i) { data[i] = other.data[i]; } } return *this; } template<typename DataT> size_t ArrayT<DataT>::Size() const{ return size; } template<typename DataT> size_t ArrayT<DataT>::Capacity() const{ return capacity; } template<typename DataT> void ArrayT<DataT>::push_back(const DataT & newData){ if (size >= capacity) { DataT * tmp; capacity *= 2; tmp = new DataT[capacity]; for(size_t i = 0; i < size; ++i) { tmp[i] = data[i]; } if (data != nullptr) { delete[] data; } data = tmp; } data[size] = newData; ++size; } template<typename DataT> const DataT & ArrayT<DataT>::operator[](size_t index) const{ return data[index]; } template<typename DataT> const DataT & ArrayT<DataT>::at(size_t index) const{ if (index < size) { return data[index]; } else { std::cout << "Array index out of bounds " << std::endl; return data[0]; } } template<typename DataT> DataT & ArrayT<DataT>::operator [](size_t index){ return data[index]; } template<typename DataT> DataT & ArrayT<DataT>::at(size_t index){ if (index < size) { return data[index]; } else { std::cout << "Array index out of bounds " << std::endl; return data[0]; } } template<typename DataT> int ArrayT<DataT>::BadFun(){ return static_cast<int>(data[0]); }