 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
blue_viking Guest
|
Posted: Mon Mar 14, 2005 9:30 pm Post subject: Question about operator= |
|
|
Hi Every one,
class Value {
int a, b;
float c;
public:
Value(int aa = 0, int bb = 0, float cc = 0.0)
: a(aa), b(bb), c(cc) {}
Value& operator=(const Value& rv) {
a = rv.a;
b = rv.b;
c = rv.c;
return *this;
}
friend ostream&
operator<<(ostream& os, const Value& rv) {
return os << "a = " << rv.a << ", b = "<< rv.b << ", c = " << rv.c;
}
};
int main() {
Value a, b(1, 2, 3.3);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
// Here the assignment operator is called
a = b;
//or in this form
//a.operator=(b);
cout << "a after assignment: " << a << endl;
} ///:~
Please have a look at the implementation of "operator=" in the above
example .
Why should one return *this from the implementation of "=" operator.
// Here the assignment operator is called
a = b;
//or in this form
//a.operator=(b);
In the above statement object is calling the "=" and why should I
return "*this" from the function? I mean I am returning "a" and storing
it agian in "a"
Why is this required?
Please explain me why should I return "*this" from overloaded "="
openator.
Thank you for the help.
Thanks,
Blue :)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Thomas Maeder Guest
|
Posted: Mon Mar 14, 2005 11:56 pm Post subject: Re: Question about operator= |
|
|
"blue_viking" <ubyalamanchi (AT) gmail (DOT) com> writes:
| Quote: | int main() {
Value a, b(1, 2, 3.3);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
// Here the assignment operator is called
a = b;
//or in this form
//a.operator=(b);
cout << "a after assignment: " << a << endl;
} ///:~
Please have a look at the implementation of "operator=" in the above
example .
Why should one return *this from the implementation of "=" operator.
|
To avoid surprising the user, user-defined types are supposed to "do
as the ints do". Using ints, you can write
int i1(3);
int i2;
int i3;
i3 = i2 = i1;
This only works because the assignment expression has type
int. Analoguously, the copy-assignment operator of class Value should
have type Value (or something similar enough).
| Quote: | Why is this required?
|
It's not strictly required, but it's considered a good idea by many
people.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
R Samuel Klatchko Guest
|
Posted: Mon Mar 14, 2005 11:58 pm Post subject: Re: Question about operator= |
|
|
blue_viking wrote:
| Quote: | Why should one return *this from the implementation of "=" operator.
|
So you can write code such as:
if ((a = foo()) != 0)
....
or:
a = b = c;
samuel
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Orjan Westin Guest
|
Posted: Mon Mar 14, 2005 11:58 pm Post subject: Re: Question about operator= |
|
|
blue_viking wrote:
| Quote: |
Please explain me why should I return "*this" from overloaded "="
openator.
|
class X
{
public:
//...
X& operator=(const & X)
{
//...
}
};
// Declare some variables
X a,b,c;
// Create an X in some function
a = b = c = GiveMeX();
Orjan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Victor Bazarov Guest
|
Posted: Tue Mar 15, 2005 3:48 pm Post subject: Re: Question about operator= |
|
|
blue_viking wrote:
| Quote: | [...]
Please explain me why should I return "*this" from overloaded "="
openator.
|
It is recommended so you can chain the assignments:
Value a, b, c;
...
a = b = c = 42;
V
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Ali Çehreli Guest
|
Posted: Tue Mar 15, 2005 3:50 pm Post subject: Re: Question about operator= |
|
|
"blue_viking" <ubyalamanchi (AT) gmail (DOT) com> wrote
| Quote: | class Value {
int a, b;
float c;
public:
Value(int aa = 0, int bb = 0, float cc = 0.0)
: a(aa), b(bb), c(cc) {}
|
Of course you are writing the following operator for demonstration purposes
only... It is not necessary to write operator= for this class, because the
compiler generated one would do the right thing.
Also, just to make sure, if you needed to write operator=, you would most
likely have to write the copy constructor and the destructor as well.
Having to write these functions is risky because one can forget to update
them after introducing a new member variable. It is easier to have types
that consist only of copyable types.
| Quote: | Value& operator=(const Value& rv) {
a = rv.a;
b = rv.b;
c = rv.c;
return *this;
}
|
The implementation above is exception safe because assignments to basic
types don't throw. It wouldn't be exception safe if the assignment operator
of any of the members could throw. For that reason, unless there is a good
reason against, operator= better be written in the now-canonical way of
using the member 'swap' function. One way is
Value & operator= (const Value & rv)
{
Value temp(rv); // do the work on the side
this->swap(temp); // swap this with the newly copied object
return *this;
} // the old state will die as 'temp'
Value::swap is a non-throwing function that swaps the members of two
objects. In this case:
#include <algorithm>
/* ... */
// Does not throw
void Value::swap(Value & other)
{
std::swap(a, other.a);
std::swap(b, other.b);
std::swap(c, other.c);
};
| Quote: | Value a, b(1, 2, 3.3);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
// Here the assignment operator is called
a = b;
|
| Quote: | Why should one return *this from the implementation of "=" operator.
|
The general answer is that Value behaves like a basic type, so that one can
link operations like
a = b = c;
In this case, first (b=c) is executed, then the result of that operation is
assigned to a. If operator= did not return *this, there would be nothing to
assign to a.
| Quote: | // Here the assignment operator is called
a = b;
//or in this form
//a.operator=(b);
In the above statement object is calling the "=" and why should I
return "*this" from the function? I mean I am returning "a" and storing
it agian in "a"
|
It is not stored back in 'a' a second time, because by defining operator=
you explicitly stopped the compiler from doing this "shallow copy." You
return *this so that the result of the operation has a type that can be used
in other operations.
This is conventional too. The users of your class would expect operator= to
return Value &. (Some users might expect it to return 'Value const &' but I
think this is an old discussion which is not that interesting anymore.)
Ali
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Madhur Guest
|
Posted: Tue Mar 15, 2005 3:53 pm Post subject: Re: Question about operator= |
|
|
Hi
u return *this to enable a=b=c
if u overload assignmemnt operator as follows
void operator(Value& rv){...}
then ur ADT can only operate a=b.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
er.rupali@gmail.com Guest
|
Posted: Tue Mar 15, 2005 4:01 pm Post subject: Re: Question about operator= |
|
|
you definately need to return this pointer here as the operator
overloading function is returning an object reference so as to make use
of = operator meaningful.
now we can write:
a=b;
a and b being two objects of the class.
where the corresponding members of two objects are made equal.
we can also do this without returning this pointer but then we need to
create a temporary object and then return it which is decreasing the
efficiency.
hope i convinced you!!!
plz let me know if i am wrong.
take care
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
John Potter Guest
|
Posted: Thu Mar 17, 2005 8:05 am Post subject: Re: Question about operator= |
|
|
On 15 Mar 2005 10:50:15 -0500, Ali Çehreli <acehreli (AT) yahoo (DOT) com> wrote:
| Quote: | "blue_viking" <ubyalamanchi (AT) gmail (DOT) com> wrote in message
news:1110814382.089261.74780 (AT) l41g2000cwc (DOT) googlegroups.com...
Value& operator=(const Value& rv) {
a = rv.a;
b = rv.b;
c = rv.c;
return *this;
}
The implementation above is exception safe because assignments to basic
types don't throw. It wouldn't be exception safe if the assignment operator
of any of the members could throw. For that reason, unless there is a good
reason against, operator= better be written in the now-canonical way of
using the member 'swap' function.
|
The swap idiom provides strong exception safety which may not be needed.
Do you have an example where a streight forward operator does not
require a test for self assignment and is not basic exception safe?
Historicly, the swap idiom emerged from the self assignment test.
John
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
kanze@gabi-soft.fr Guest
|
Posted: Thu Mar 17, 2005 1:10 pm Post subject: Re: Question about operator= |
|
|
Ali Çehreli wrote:
| Quote: | "blue_viking" <ubyalamanchi (AT) gmail (DOT) com> wrote in message
news:1110814382.089261.74780 (AT) l41g2000cwc (DOT) googlegroups.com...
class Value {
int a, b;
float c;
public:
Value(int aa = 0, int bb = 0, float cc = 0.0)
: a(aa), b(bb), c(cc) {}
Of course you are writing the following operator for
demonstration purposes only... It is not necessary to write
operator= for this class, because the compiler generated one
would do the right thing.
|
Maybe. The semantics of the compiler generated assignment
operator are correct, but a function or operator is more than
just semantics. The compiler generated version is inline, which
is generally not desirable. It is also public, which may not be
desirable either. (Although I agree that in this particular
case, both are probably acceptable.)
| Quote: | Also, just to make sure, if you needed to write operator=, you
would most likely have to write the copy constructor and the
destructor as well.
Having to write these functions is risky because one can
forget to update them after introducing a new member variable.
It is easier to have types that consist only of copyable
types.
|
Actually, my preferred solution is to not support copy or
assignment until I determine that they are really necessary:-).
| Quote: | Value& operator=(const Value& rv) {
a = rv.a;
b = rv.b;
c = rv.c;
return *this;
}
The implementation above is exception safe because assignments
to basic types don't throw. It wouldn't be exception safe if
the assignment operator of any of the members could throw.
|
Of course it would. It wouldn't give the strong guarantee, but
there are many cases where the strong guarantee isn't needed.
[...]
| Quote: | Why should one return *this from the implementation of "="
operator. |
| Quote: | The general answer is that Value behaves like a basic type, so
that one can link operations like
a = b = c;
|
Independantly of what one can or cannot do, the real answer is
that a user defined operator should act like the same operator
for built in types. Way back when, there were long discussions
concerning whether the reference returned by operator= should be
const or not. As far as I can see, returning a const reference
allows all reasonable uses, and protects against a few types of
errors. But it isn't what the built-in (nor the compiler
generated) operator does.
[...]
| Quote: | This is conventional too. The users of your class would expect
operator= to return Value &. (Some users might expect it to
return 'Value const &' but I think this is an old discussion
which is not that interesting anymore.)
|
Agreed. I think a consensus has been reached on the subject.
I'd say that the "conventional" part is the killer argument.
There are doubtlessly cases where one could argue that no one in
their right mind would want to do something like "a = b = c".
Even in such cases, however, operator= should return a reference
to itself. It's the convention, and anything else raises (or
should raise) questions.
--
James Kanze GABI Software
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|