Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

LAB 12 Please Comments in code explain what's being done and dvide the code into .h and .cpp files. Thank you very much. Create a

LAB 12

Please Comments in code explain what's being done and dvide the code into .h and .cpp files. Thank you very much.

Create a template class called MyArray that implements an array and works with any type (int, double, etc.). The constructor should take a size for the array and use new to allocate memory (don't forget to delete in the destructor). Overload operator[] to access the elements of the array. If an attempt is made to access an element outside the array bounds (either above OR below), throw an exception. In the main program, first create a MyArray object, add a few values, and demonstrate that operator[] throws an std::out_of_range if an attempt is made to access an out-of-bounds element (out-of-bounds means above OR below the array bounds). Catch the exception and print an appropriate message. Then do the same thing with an MyArray. Be sure to test both GOOD and BAD index values.

Hint: you will need both of these overloads, which will have identical implementations (something along the lines of "if (something) return a value")

T& operator[](int i)

const T& operator[](int i) const

Note that both of these operator[] overloads return a reference to an object of type T. Your MyArray class has an array of these objects. For example, to return a reference to the first element in the array, you would use return array[0];

Optional Challenge: Create a method called

void CheckBounds(int i)

that simply returns if i is a valid subscript for the array, and throws a std::out_of_range exception otherwise. Use this method in your operator overloads.

Checklist

1. Uncheck the Create directory for solution checkbox in the New Project Dialog 2. Project/solution named correctly 3. Correct comments at top 4. Consistent indentation (Use Edit/Advanced/Format Document) 5. Good variable names 6. Overall neat organization 7. Comments in code explain what's being done 8. Correct division of code into .h and .cpp files 9. Use of #pragma once in .h files (or, #ifndef) 10. #include "stdafx.h" in cpp files (or, suppress pch) 11. Test for below as well as above out-of-range

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions