Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the C++ DynArray class. Here is a brief description of all of the class fu

ID: 3631765 • Letter: W

Question

Write the C++ DynArray class. Here is a brief description of all of the class functions that your class should include:
• No-argument constructor – initializes a DynArray object to being empty.
• One-argument constructor – uses dynamic memory allocation to obtain a contiguous block of memory for storing n int values, where n is its argument.
• show – displays the nth element in the DynArray. If the DynArray is empty or if n is an invalid index, this function should generate an error message.
• set – will set the nth element in the DynArray to x, where n is the value of its first argument and x is value of its second argument. If the DynArray is empty or if n is an invalid index, this function should generate an error message.
• expand – will take an existing DynArray and expand its size by its argument, s. Hint: To expand a DynArray, allocate a new, larger block of dynamic memory, copy the values from the old DynArray to the new memory, and deallocate the old memory.
• A destructor to deallocate dynamic memory when a DynArray object passes out of scope.

Explanation / Answer

/*Error class to handle array out of bounds exception

array size exception*/

class Errors

{

public :

void ArrayIndexoutOfBounds()

{

cout<<"Array index out of bound Exception"<<endl;

}

void lessSizeArray()

{

cout<<"newArray size should be greater than old Array"<<endl;

}

};

/*DynArray class inheriting the Errors class */

class DynArray:public Errors

{

//two pointers to point to address of two dynamic arrays

int*intList;

int *newList;

//size of array

int arraySize;

public:

//constructor

DynArray()

{

intList=NULL;

}

//constructor with arraySize argument

DynArray(int arraySize)

{

//allocate memory dynamically

intList=new int[arraySize];

}

void show(int index)

{

//To handle the out of bounds array exception

if(index>arraySize)

throw ArrayIndexoutOfBounds;

else

cout<<"Element at index="<<intList[index];

}

void set(int index,int x)

{

//To set the new element into array index

for(int i=0;i<arraySize;i++)

if(index==i)

intList[index]=x;

}

void expand(int newSize)

{

//new array size always greater than old array

//or else thow exception

if(newSize<arraySize)

throw lessSizeArray;

else

{

//allocate memory for new array

newList=new int[newSize];

//copy old elements into newly created array newList

for(int i=0;i<arraySize;i++)

newList[i]=intList[i];

}

}

//Destructor

~DynArray()

{

delete[] newList;

delete[] intList;

}

};

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote