Crash when accessing not-in-range index in array

Hello.

I've made my own template Array class, and these are the operator[] overloadings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
GType& operator[](int Index)
{
	if (Index >= 0 && Index < size)
	   return array_type[Index];

        // cout for test purpose
        else
           cout << "Invalid index";

}

const GType& operator[](int Index) const
{
	if (Index >= 0 && Index < size)
	   return array_type[Index];

        // cout for test purpose
        else
           cout << "Invalid index";
}


In the main function, when I write

1
2
3
4
5
// Create an array of 1 element
GArray<int> my(1);

// Access the 5th element (BAD!)
my[5] = 55;


This makes my program crash.

Why?

In my operator overloading function I put an if that should prevent this situation! But it doesn't...
Last edited on
You still have to return something from your function. What makes sense to return when you have an index out of bounds? Either that, or you throw an exception and every time you do an array access out of bounds and be ready to catch it in your calling code.
Last edited on
Topic archived. No new replies allowed.