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

Using the above UML for your specification, implement a class that contains a dy

ID: 671490 • Letter: U

Question

Using the above UML for your specification, implement a class that contains a dynamically allocated array. The size of the array is specified through it's constructor which initializes the object by creating the array and setting capacity to the size of the array. The destructor is responsible for deallocating the array. set() is responsible for assigning value v to element i in the array. It returns -1 if there is an error ( array index out of bounds). 0 otherwise. get() is responsible for retrieving a value at the i'th element and returning it through reverence parameter v. It returns -1 if there is an error ( array index out of bounds), 0 otherwise. Get Length() returns the capacity of the array. print() prints the current contents of the array. Submit your class in it's own header file. MyArray.h. Do not write a program, just submit the class in it's own header file. I will test your class with my own test program that will create a MyArray object and test each method.

Explanation / Answer

#include <iostream>
using namespace std;
class MyArray
{
int *a;
int capacity;
  
public:
MyArray(int c);
~MyArray();
int set(int i, int v);
int get(int i, int &v);
void print();
int getLength();
};

MyArray::MyArray(int c)
{
a = (int *)calloc(sizeof(int), c);
capacity = c;
}
MyArray::~MyArray()
{
free(a);
a = NULL;
}

int MyArray::set(int i, int v)
{
if(i >= capacity)
return -1;
*(a+i) = v;
return 0;
}

int MyArray::get(int i, int &v)
{
if(i >= capacity)
return -1;
v = *(a+i);
return 0;
}

void MyArray::print()
{
for(int i = 0; i < capacity; i++)
cout<<*(a+i)<<" ";
}

int MyArray:: getLength()
{
return capacity;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote