c++ program that Design and implement a class named SafeArray which solves the a
ID: 3768826 • Letter: C
Question
c++ program that Design and implement a class named SafeArray which solves the array index out of bounds problem and also allows the user to begin the array index starting at any integer, positive or negative. Every object of type SafeArray is an array of type int. During execution, when accessing an array component, if the index is out of bounds, the program must throw exception to handle the error. You will define your own exception class which will display the index out of bound error message. Consider the following statements:
SafeArray list(5) // declares list to be an array of 5 integers, list[0], list[1]……list[4]
SafeArray posList(2, 10) //declares posList to be an array of 8 integers, posList[2], posList[3}……. posList[9]
SafeArray negList(-2,10) //declares negList to be an array of 12 integers, negList[-2], negList[-1], negList[0].. ……negList[9]
A SafeArray header file is given and your just need to implement the member functions and test your class with each scenario in your main program.
Explanation / Answer
c++ Code:
#include <bits/stdc++.h>
using namespace std;
class SafeArray{
public:
int * arr;
int start_index;
int end_index;
SafeArray(int n){
arr=new int[n];
start_index=0;
end_index=n-1;
}
SafeArray(int n,int m){
arr=new int[m-n];
start_index=n;
end_index=m-1;
}
void set(int index,int value){
if(start_index<=index && index<=end_index){
arr[index-start_index]=value;
}
else{
throw "Index out of bound";
}
}
int get(int index){
if(start_index<=index && index<end_index){
return arr[index-start_index];
}
else{
throw "Index out of bound";
}
}
};
int main(){
SafeArray l(-2,3);
for(int i=0;i<5;i++){
l.set(i-2,i+2);
}
cout<<l.get(-1)<<endl;
return 0;
}
For testing purpose I have created an SafeArray of size 5 i.e from -2 to 2 .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.