Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ Moderated > Re: assignment ...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 6 of 6 Topic 9519 of 9831
Post > Topic >>

Re: assignment operator using a constructor

by Tony Delroy <tony_in_da_uk@[EMAIL PROTECTED] > Apr 21, 2008 at 12:15 PM

On Apr 21, 6:48 am, "Jeff Baker" <algort...@[EMAIL PROTECTED]
> wrote:
> Using this to start. base& and *this is the correct form.
>    base  operator=(const base & a){cout << "assignment operator  " <<
a.s <<
> endl; return a.s;}
>
> int operator=(const base& a){cout << "asignment operator " << a.s <<
endl;
> return a.s};
>
> ...
> base operator =(/...../){}
>
> Which is more efficient the int operator as written or the base type as
> written?
> I understand that it might be preferred to use one over the other
determined
> how a problem is handled.

While the language doesn't force it, operator= should always return a
reference to the assigned-to object (i.e. return *this;).

This usage is expected: e.g. it will really confuse your users if
   if ((my_var = new_value).is_valid()) ...
is not equivalent to
   my_var = new_value;
   if (my_var.is_valid()) ...

Similarly, one might hack up a class for which:
    a < b < c
tests a < b && b < c (rather than the equivalent if "(a < b ? 1 : 0) <
c".  I think it's part of the C++ learning process to hack up and try
out a few of these things.  But despite the superficial appeal, you'd
find it will typically create subtle "issues" and unmaintainable code
(much faster if you throw in implicit constructors and conversion
operators).

In conclusion, there are just some things you don't mess with, and
assignment operator return types are one of them.  Another one's
operator<< return type....

Tony

-- 
      [ See http://www.gotw.ca/resources/clcm.htm
for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
 




 6 Posts in Topic:
assignment operator using a constructor
"Jeff Baker" &l  2008-04-18 15:00:17 
Re: assignment operator using a constructor
arch119 <shambhushrest  2008-04-19 01:45:54 
Re: assignment operator using a constructor
=?UTF-8?B?RXJpayBXaWtzdHL  2008-04-19 02:01:56 
Re: assignment operator using a constructor
Martin York <Martin.Yo  2008-04-19 02:02:15 
Re: assignment operator using a constructor
"Jeff Baker" &l  2008-04-20 15:48:02 
Re: assignment operator using a constructor
Tony Delroy <tony_in_d  2008-04-21 12:15:18 

Post A Reply:
  Go here to Signup

AddThis Feed Button


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

Contact
tan12V112 Sat Jul 26 2:47:15 CDT 2008.