On Fri, 17 Jul 2015 08:30:13 -0700 (PDT), fl <
rxj...@gmail.com>
wrote:
>Hi,
>
>I find the following code snippet on line. I feel that is interesting for my
>learning.
>
>This part is difficult to understand for me.
>
> cBase*& operator[](unsigned index)
Does it make sense to you if the & were not there. The function would
return a value. That value would have type "pointer to cBase." By
way of example, strcpy also returns a value. That value has type
pointer to char.
Now put the & back in. Now the function returns a reference. That
reference "refers" to an object of type "pointer to cBase".
> {
> // much more complicated, but simplified for example
> return array[index];
Obviously, the reference being returned refers to the object
array[index].
> }
>
>Could you explain it to me?
>'*&' looks weird I feel.
>
>Thanks,
>
>
>
>.......
>// the classes
>class cBase {};
>class cDerived : public cBase {};
>
>class cBaseArray
>{
> // the array of pointers to cBase
> cBase** array;
array has type cBase**. This means that cBase points to an object of
type cBase*. From the context, it appears obvious the object cBase
points to is followed in memory by several more objects of the same
type. Normal array notation allows array[0] to designate the first of
these objects, array[1] the second, etc. array[index] designates one
of these objects, which one being determined at run time.
> // overloaded operator that returns an element of the array
> cBase*& operator[](unsigned index)
> {
> // much more complicated, but simplified for example
> return array[index];
Since all the objects pointed to by array have type cBase*, object
array[index] has this type. The reference that is returned designates
this object. This allows the calling function to use this reference
to access the cBase object array[index] points to. It also allows the
calling function to change the value in array[index] itself so that it
points to some other object of type cBase.
If the & were missing, the calling function would receive the value of
array[index] and could access the cBase object pointed to but could
not change the value of array[index] itself.
Whether the calling function should be allowed to change a value in
one of the array objects is a different question.
> }
>};
--
Remove del for email