|
-
April 2nd, 2007, 10:17 AM
#1
Returning by reference
Code:
class Foo
{
int data;
public:
Foo (int n):data (n)
{
}
Foo ():data (0)
{
}
Foo &operator= (int n)
{
data = n;
return *this;
}
Foo &operator= (const Foo& foo)
{
data = foo.data;
return *this;
}
void display ()
{
cout << "data = " << data << endl;
}
};
Why in the above code the operator= returns by reference? If I return it by value (Foo operator= ()) it seems to work fine. Do we return by refernce because it is faster (only the address of the object will be returned instead of making a copy of the object and then returning it, please correct me if I'm wrong )?
Thanks.
"I rather not play football than wear Nerrazzuri shirt" - Paolo Maldini
FORZA MILAN!!!
-
April 2nd, 2007, 10:25 AM
#2
Re: Returning by reference
To be able to do something like:Albert.
Please, correct me. I'm just learning.... and sorry for my english :-)
-
April 2nd, 2007, 10:54 AM
#3
Re: Returning by reference
Hi Albert,
your assignment can be done with return by value operators, too. References are returned to modify the return value in a later expression:
Code:
// assign a + b to c, multiply c by d and store the result in c.
(c = a + b) *= d;
This cannot be done by returning by value, because it changes a temporary object only, leaving c untouched (after it has been assigned a+b), so you have to return by reference.
Regards,
Guido
- Guido
-
April 2nd, 2007, 11:18 AM
#4
Re: Returning by reference
Hi Guido,
Really? So, I was wrong!!! I thought the reference was necessary to make the last assignationThanks.
Albert.
Please, correct me. I'm just learning.... and sorry for my english :-)
-
April 2nd, 2007, 03:43 PM
#5
Re: Returning by reference
Guys, thank you for the responses [ ].
"I rather not play football than wear Nerrazzuri shirt" - Paolo Maldini
FORZA MILAN!!!
-
April 3rd, 2007, 03:58 AM
#6
Re: Returning by reference
It's also for efficiency.
Code:
Foo &operator= (const Foo& foo)
{
data = foo.data;
return *this;
}
-
April 3rd, 2007, 06:56 AM
#7
Re: Returning by reference
 Originally Posted by AlbertGM
Hi Guido,
Really? So, I was wrong!!! I thought the reference was necessary to make the last assignation Thanks.
Albert.
Partly true, not wrong.
Regards,
Ramkrishna Pawar
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|