I get an error saying I cannot convert an 'int' to 'int &'. I want it to return something to indicate that it's an invalid cell like a boolean somewhat. That way we can know if it was successful or not when trying to modify/access the array element. Got any idea how this can be done?

You can't return -1 or any other literal value. You could have a static member and return that, but it doesn't really make much sense, especially since you are returning a non-const reference.

I would do what vector does for operator[] and just define it as undefined behavior. Then you can return m_array[0] or m_array[m_size] just to suppress the compiler's warning and actually do something.

You could also do what vector does for at() and throw an exception. If you program or library uses exceptions then this might be the better and safer way to go. Simply throwing std::out_of_range should be fine.

>> if ((p_index >= 0) && (p_index <= m_size))
BTW, that should probably be p_index < m_size, not <=. And don't forget to create a const version of the operator.

I would do what vector does for operator[] and just define it as undefined behavior. Then you can return m_array[0] or m_array[m_size] just to suppress the compiler's warning and actually do something.

I'm not sure how vector does it. What do you mean as an undefined behavior? I don't know if this would make much sense...

I guess a Get() function would work, but it would be convienent to have it in a [] operator too so I'm not getting two differnet behaviors.

That's no good either. If the size is zero then you're still accessing out of bounds.
Best option is to change the if statement into an assert, and just always return m_array[p_index].
Or you can use exceptions.
Or if you really want to you can return a reference to a static Datatype.

My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger

Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

I'm not sure how vector does it. What do you mean as an undefined behavior? I don't know if this would make much sense...

In other words, do not do any bounds checking. It is up to the user of the class to ensure that only valid indices are used.

Originally Posted by Bjarne Stroustrup (2000-10-14)

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.