 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
metalbr@gmail.com Guest
|
Posted: Wed May 16, 2007 4:21 am Post subject: Diferences between "A& operator = (A& a)" and "A& operator = |
|
|
class A{
public:
A operator - (int i){
return A();
}
A& operator = (A& a){ // if A& operator = (const A& a) works!!!
return *this;
}
};
int main(){
A a, b;
a = b; // ok
a = b + 1; // error, why? why const is necessary?
}
Thanks!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
John Moeller Guest
|
Posted: Wed May 16, 2007 7:01 am Post subject: Re: Diferences between "A& operator = (A& a)" and "A& operat |
|
|
metalbr (AT) gmail (DOT) com wrote:
| Quote: | class A{
public:
A operator - (int i){
return A();
}
A& operator = (A& a){ // if A& operator = (const A& a) works!!!
return *this;
}
};
int main(){
A a, b;
a = b; // ok
a = b + 1; // error, why? why const is necessary?
}
Thanks!
|
I assume you mean "b - 1", and not "b + 1". The result of b - 1 is a
temporary object. You can't pass a temporary to a function with a
non-const reference, because you can only bind an rvalue to a const
reference. That's why your operator=(const A&) works and operator=(A&)
doesn't.
--
John Moeller
fishcorn (AT) gmail (DOT) com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
Abhishek Padmanabh Guest
|
Posted: Wed May 16, 2007 7:04 am Post subject: Re: Diferences between "A& operator = (A& a)" and "A& operat |
|
|
On 16 May, 09:21, "meta...@gmail.com" <meta...@gmail.com> wrote:
| Quote: | int main(){
A a, b;
a = b; // ok
a = b + 1; // error, why? why const is necessary?
|
Because b+1 results in a temporary A to be created, with the result of
addition and then invoke operator= with that temporary as the second
argument to it. That (the temporary) cannot be bound to a reference to
non-const.
--
[ 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
|
|