Search code examples
c++visual-studio-2012template-classes

testing "Try and Catch"


In this program, I am using template class, I have a header file and this is my main file. I am having trouble displaying the (".....") IndexOutOfBounds and displaying it on the screen.

#include "XArray.h"
#include <iomanip>
#include <string>

using namespace std;


template<class T>
void afriend ( XArray<T> );


int main()
{
XArray<double> myAD(18);
myAD.randGen(15, 100);

cout << myAD.getType() << endl;
cout << setprecision(1) << fixed << "\n\n Unsorted:     " << myAD;

myAD.sort();
cout << "\n Now Sorted:     " << myAD;
cout << "\n\n";

**try
{
    cout << "A[-5]      = " << setw(6) << myAD[-5] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
    e.print();
}
try
{
    cout << "A[8]       = " << setw(6) << myAD[8] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
    e.print();
}**



cout << "\n\n" << setprecision(2) << fixed;
cout << "Size               = " << setw(6) << myAD.getSize() << endl;
cout << "Mean               = " << setw(6) << myAD.mean() << endl;
cout << "Median             = " << setw(6) << myAD.median() << endl;
cout << "STD                = " << setw(6) << myAD.std() << endl;
cout << "Min #              = " << setw(6) << myAD.min() << endl;
cout << "Max #              = " << setw(6) << myAD.max() << endl;



return 0;
}

There is the Array.h file posted as a dropbox link

Array.h

The code for operator[] in Array.h is:

template <class T>
T XArray<T>::operator[] (int idx)
{
    if( (idx = 0) && (idx < size) )
    {
        return Array[idx];
    }

    else
    {
        throw IndexOutOfBound();
        return numeric_limits<T>::epsilon();
    }
}

Solution

  • The problem is in the operator[] function. The code idx = 0 sets idx to 0. So all of your calls to operator[] will return the first element, and therefore there is no out-of-bounds error unless the array is empty.

    You probably meant to write if ( idx >= 0 && idx < size ).

    BTW the throw aborts the function, it makes no sense to return after throw.