Answer to Question #193424 in C++ for VASANTH V

Question #193424

Define a class Array which can hold 5 elements of type int. Define a member function int Get(int index); which returns the indexth element of the array if index is between 0 to 4 and throws an exception if index is out of bounds. Catch the exception in the main program and print an error.


1
Expert's answer
2021-05-16T12:23:42-0400
#include <iostream>


using namespace std;


class Array{


private:
    int elements[5] = {1,2,3,4,5};


public:
    int Get(int index)
    {
        if(index>=0 && index<=4)
            return elements[index];
        throw exception();
    }
};




int main()
{
    Array myArray;
    try{
        cout << myArray.Get(5) << endl;
    }
    catch(exception e)
    {
        cout << "index out of bounds " << endl;
    }


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog