Re: Operator Cast () Reference?
Immortal Nephi <Immortal_Nephi@hotmail.com> writes:
Someone posted his Byte class code on the previous thread. I have a
question about operator cast ().
I think that would be me.
Please explain the difference
between local object and reference object. Why do you need reference
object?
If you remember, the Byte class was introduced as a `proxy' for your
Array class, which stored a pointer to an array of unsigned char. A
Byte instance was returned by your Array::op[], so:
Byte Array::operator[](int index) { return pData[index]; }
It is created from pData[index] using the non-explicit constructor:
Byte::Byte(unsigned char&);
You will see that it stores the unsigned char at pData[index] *by
reference*. This is the whole point of using the proxy. Basically it
`represents' the stored data so that any operation upon the proxy is
*really* an operation upon the data it represents (stores).
The reason that you need:
Byte::operator unsigned char&();
and not:
Byte::operator unsigned char();
is that you need to allow assignment to the underlying unsigned char
through a Byte proxy. Consider:
Array array(4);
// ...
array[0] = 42U;
The last call is equivalent to:
Byte b(array[0]);
b.operator unsigned char&() = 42U; // LHS returns reference to array[0]
Using a reference here 42U gets assigned to the actual unsigned char at
array[0]. If you consider the alternative, which would be:
Byte b(array[0]);
b.operator unsigned char() = 42U; // LHS returns *temporary*
// array[0] *not* changed
then what you would be attempting to do is assigne 42U to a *temporary*
returned by b.operator unsigned char(), which is not what you want.
Regards
Paul Bibbings