Hi all
This seems to me a peculiar problem, but confounding nonetheless...
The problem seems to be that an overloaded subscript operator isn't being called unless it is called explicitly
-
struct myStruct
-
{
-
myStruct& operator[] (int index)
-
{
-
return *(this + index);
-
}
-
-
bool val1;
-
int val2;
-
float val3;
-
double val4;
-
};
-
-
int main()
-
{
-
myStruct *s = new myStruct[5];
-
s[0].val1 = true;//works, but does not call the overloaded operator
-
s->operator[](0).val1 = 1;//calls the overloaded operator - also works
-
-
...
-
}
-
I can't find anything on the Internet or any textbooks about this. Any clues as to why this doesn't work would be appreciated.
Thanks, Greg
I'm not completely sure about this, but allow me to give you an educated guess:
In your first example s[0].val1 = true; you are using the subscript operator on the pointer. This will return the first myStruct in the array - you can then access val1 correctly. However, the subscript operator is called on the pointer, not the struct.
In your second example s->operator[](0).val1 = 1; the -> is evaluated on the pointer first, giving you the myStruct at s (Since s is a pointer to an array, it will return the first element of the array). Then you call the subscript function explicitly.
You may be able to use the overloaded function like this:
- myStruct *s = new myStruct[5];
-
s[0][0].val1 = true;
As an aside, what are you trying to accomplish by overloading the [] operator? It looks like you are treating the object as an array, but it will actually give you the address in memory index slots in front of the object, which will be pointing to random, garbage memory.