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

In lecture we worked with the SafeArray class. From the user\'s perspective it w

ID: 3843618 • Letter: I

Question

In lecture we worked with the SafeArray class. From the user's perspective it worked like an array with some additional neat extra features. SafeArray() - will allocate a one dimensional integer array with default size of 100 and which can be indexed between 0 and 99. Safe Array (int n) - will allocate a one dimensional integer array with size of n and which can be indexed between 0 and n - 1. SafeArray(int m, int n) - will allocate a one dimensional integer array which can be indexed between m and n. A destructor: -SafeArray() An overloaded function "[]" to allow update of and retrieval from SafeArray An assignment operator Recall that one of the things that we can do with an standard C++ array is use its name as a pointer so that a[i] is equivalent to *(a+i) via dereferencing. We would to do the same thing with our Safe-Arrays. e.g. SafeArray a(10); *(a+3) = 100;//same as a[3]=100 What support function(s) might you need to write to get the dereferencing to work for the SafeArray class? Make sure that your write each function that you need in order to make this work. Explain your idea.

Explanation / Answer

#include <iostream>

using namespace std;

class SafeArray
{
    int *a; //integer pointer to hold array
    int size; //Holds the size of the array
public:
    SafeArray() //default constructor
    {
        size = 100;
        a = new int[size]; //Allocating memory for the elements
    }
    SafeArray(int n) //parameterized constructor
    {
        //Creating array for elements
        size = n;
        a = new int [size];
    }
    SafeArray(int m, int n) //Another parameterized constructor
    {
        //creating array of size n
        size = n;
        a = new int [size];
    }
    ~SafeArray() //Destructor
    {
        delete a; //Deallocating memory
    }
    //overloading operators
    int& operator [](int i) //overloading [] for update and retrieval
    {
        return a[i];
    }
    void operator = (SafeArray x) //Overloading = operator
    {
        size = x.size;
        a = new int[size];
        for(int i = 0; i < size; i++)
            a[i] = x.a[i];
    }
    friend int* operator +(SafeArray, int); //declaring function operator + as friend
};

//Support function to make dereferencing work
int* operator + (SafeArray x, int i) //overloading operator +
{
    return (x.a + i); //returning pointer of the specific location
}

int main()
{
    SafeArray a(10);
    *(a + 3) = 100; //updating the value of the pointer returned
    return 0;
}

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