Ulrich Eckhardt wrote:
> chuck wrote:
>> I have a class whose data members are constant. So, default
>> assignment will not happen. I am trying to write and assignment
>> operator method that will allow assignment.
>
> Ian already said it, but I would say the same but a bit differently: if
your
> object has constants, these constants either don't participate in the
> assignment operation or the whole object can subsequently not be
assigned.
> Otherwise, it might simply have been the wrong choice to make them
> constants in the first place. If you do***ented what the 'i' in the
class
> below is supposed to represent, it would be possible to say whether it
> should be constant or not and whether the class as a whole should be
> copyable.
>
>> struct A {
>> const int i;
>>
>> A (int i) : i (i)
>> {}
>
> You might want to make this 'explicit A(int i)..'.
>
>> A operator = (A other){
>
> Aw, no. Please reread the paragraph in your book that explains how to
write
> an assignment operator. In particular pay attention to where it p*****
> references, in one case, this is actually im****tant and not just a waste
of
> performance.
>
>> A temp = A(other);
>
> 'other' is already an A, so why create a copy of that A in order to feed
it
> to the copy-constructor of A? If you want a copy, just write it like
these
> two:
>
> A tmp1(other);
> A tmp2 = other;
>
> Note that these are equivalent, provided 'other' is an A, otherwise the
> second form (and your's above, too!) would have invoked operator= which
> would have caused endless recursion here.
No that is untrue. The '=' in a declaration/definition has nothing to do
with assignment. The result of the code is to convert other to A and
then copy it to tmp2 (effectively the same as the OP's last declaration
statement.


|