accesing a class's overloaded [] via a pointer
Hello,
Hope someone can help me with this. I have searched the web with no luck.
I have an array class that I create instances of dynamically. However when I attempt to use the overloaded operators using my class pointers I get errors and/or unexpected results.
If I declare the object in the function (not use a passed pointer to the object declared elsewhere) it works fine, but the pointer does not.
The pertinent code is (I hope it is clear.):
Code:
class RANGE_ARRAY
{
private:
UINT* _array;
int _size;
public:
RANGE_ARRAY()
{
_array = new UINT[8];
_size = 8;
};
UINT& operator [] (int index)
{
if (index >= 0 && index < _size)
return _array[index];
};
};
void fakeUseRange(RANGE_ARRAY* ra)
{
int count = 0;
while (count < 8)
{
ra[8] = 68;
}
return;
}
Ahaaa!!! Thank you Sebastiani!
yes, typos. I omitted the else return, since I didn't think it was necesary to understand the problem at hand.
Re: Ahaaa!!! Thank you Sebastiani!
Quote:
Originally posted by mnj
yes, typos. I omitted the else return, since I didn't think it was necesary to understand the problem at hand.
the thing is, you are making a check in code to see if the index is in range, but you aren't doing anything about it. the check might as well not be there if you aren't throwing an exception or making an assertion or anything. right now your function will just return garbage and the person using the function will be oblivious to his mistake.
also, an alternative way of accessing the overloaded [] is by using it by name (but I wouldn't recommend it because of readability)
ra->operator []( 8 ) = 68