Writing a 2D class wrapped as a 1D array

I'm trying to make a 2D array class so I can deal with them more easily, by creating a dynamically allocated a 1D array. I've gotten up to writing the () operator, but I'm not sure what I should do if the row / column is out of bounds. How should I treat this? Should I throw an exception? Or something else?

1
2
3
4
5
6
7
8
9
template <typename T>
T Array<T>::operator() (Array::uint_t row, Array::uint_t col) const
{
    if (row < _rowSize && col < _colSize)
        return _ptr[(row*col)+col];
    else
        // The given row or col are out of bounds!
        return ????;
}
First, why don't you make operator() return a reference?

Also, you could try to return a special value of type T, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<typename T>
struct Array{
	private:
		//your private stuff
	public:
		//your public stuff
		T aoob;//Array Out Of Bounds
		static const T caoob=0;//Const Array Out Of Bounds
		T& operator()(unsigned x,unsigned y){
			if(x>width || y>height){
				return aoob;}
			return data[y*width+x];}
		const T& operator()(unsigned x,unsigned y) const{
			if(x>width || y>height){
				return caoob;}
			return data[y*width+x];}
		//other stuff
		};
I would go with the "throw an exception" route.

Returning a special out-of-bounds value will only mask the runtime error. Basically if you step out of bounds you might not immediately notice, and your program might just start acting weird... making it harder to debug.

On the other hand throwing an exception is very hard to miss. It draws attention to exactly when and where you're stepping out of bounds... making it much easier to find and fix.
Last edited on
@ PiMaster
Oops, I should a reference there. Thanks! So in your example, what would happen if I tried to do something with value aoob? or caoob? For example, if I were using my array class to create a 2D array of images, what would returning 0 (essentially caoob) do?

@ Disch
I've heard that C++'s exception handling is...well, bad. I've avoided working with it too much as a result...but unless I can figure out a better solution, I think that I'll probably do so.

Thanks for the quick replies!

edit: typos
Last edited on
Topic archived. No new replies allowed.