Talk About Network

Google





Programming > C - C++ Learning > Re: assigmnet o...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 6 Topic 4087 of 4400
Post > Topic >>

Re: assigmnet operator when class data members are immutable

by Ulrich Eckhardt <doomster@[EMAIL PROTECTED] > Mar 30, 2008 at 07:51 AM

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.

Uli
 




 6 Posts in Topic:
assigmnet operator when class data members are immutable
chuck <noemail@[EMAIL   2008-03-29 19:10:49 
Re: assigmnet operator when class data members are immutable
Ian Collins <ian-news@  2008-03-30 13:51:10 
Re: assigmnet operator when class data members are immutable
Ulrich Eckhardt <dooms  2008-03-30 07:51:32 
Re: assigmnet operator when class data members are immutable
Francis Glassborow <fr  2008-03-30 11:38:49 
Re: assigmnet operator when class data members are immutable
Ulrich Eckhardt <dooms  2008-03-30 18:18:38 
Re: assigmnet operator when class data members are immutable
Francis Glassborow <fr  2008-03-30 11:43:06 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
localhost-V2008-12-19 Wed Jan 7 13:45:50 PST 2009.