"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:42***************@gascad.at...
Dave Moore wrote:
"Mykhaylo Khodorev" <ra*****@chicagocentre.com.ua> wrote in message
news:cu*********@news.dg.net.ua... Hi, all
I've created a class derived from CObArray. The declaration of operator [] of CObArray looks like:
CObArray* operator [] (int nIndex) const;
CObArray*& operator [] (int nIndex);
I understand first operator is for getting data from array and
second one is for writing data to array. But I can't understand how to
implement second type of operator. How can I get a data to write to array?
Thanks.
Mykhaylo
It should be automatic .. that is the whole point of using a reference.
The first is for expressions like:
b=a[i];
and the second is for expressions like:
a[i]=b;
Which is exactly not true.
The truth is: You can't differentiate (at least not with the above)
between 'reading' and 'writing' through operator[]. One would need a proxy class
to implement this feature.
The const form of the operator is used (as any other const member
function) if it is the only one availabe or if the object by itself is const. The
other one is used in all other cases.
so in
CObArray test;
test[2] = 5;
i = test[2];
The same operator[] (the non const version) is used in both
cases, since 'test' is not const.
Whereas in
const CObArray test;
test[2] = 5;
i = test[2];
again the same operator[] (this time the const version) is used
in both cases.
I can see how my explanation may have been a bit unclear, but I don't think
it was incorrect. The point I was trying to make is that only the non-const
version can be used on the left-hand side of an expression without
generating an error, because the temporary returned by value from the const
version is an rvalue. It is of course true that the non-const version will
be called when operator[] is called for a non-const object, or through a
pointer or reference to non-const. I should have been more precise in my
original reply, sorry.
There is one further issue with the OP's example however, since the
operator[] functions there return a pointer (or a reference to a pointer).
I am not completely certain that a temporary pointer value (as returned by
the const version) cannot be used as a lvalue. I have never dealt with this
particular case before, and it may have ramifications I am not aware of.
However my intuition is that it would only mean that attempts to use the
const version on the left hand side of an assignment expression would no
longer generate a compile-time error.
Dave Moore