C++ Dynamic Array Function Below I have the functions from the .h file and I nee
ID: 3784849 • Letter: C
Question
C++ Dynamic Array Function
Below I have the functions from the .h file and I need help with the constructor!
template <class dynElem>
class dynarr {
private:
int capacity;
dynElem *A;
public:
dynarr() : capacity(0), A(NULL);
dynarr(int N): capacity(N), A(new dynElem[N]){}
dynarr(const dynarr<dynElem> &other);
~dynarr();
dynarr<dynElem> & operator=( const dynarr<dynElem> &other);
dynElem & operator[](int ndx) throw(InvalidIndex);
int getCapacity();
void reserve(int newcap);
// if newcap <= capacity, does nothing;
// if capacity is 0, allocates a dynamic array of
// capacity newcap and makes A point to that array;
// otherwise allocates a new dynamic array newA of capacity
// newcap, copies values in A to newA, deletes A and sets
// A equal to newA
};
Constructor function
template <class dynElem>
dynarr<dynElem>::dynarr(const dynarr<dynElem> &other)
{
}
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
template <class dynElem>
dynarr<dynElem>::dynarr(const dynarr<dynElem> &other)
{
// setting capacity of array from other array's capacity
capacity = other.getCapacity();
// creating array of size capacity
A = new dynElem[capacity];
// now copying other's elements to A, using overloaded operator [](as defined in .h file)
for(int i=0; i<capacity; i++){
A[i] = other[i];
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.