c++ and return by reference

JetBlack69

Diamond Member
Sep 16, 2001
4,580
1
0
So I'm reading a C++ book by O'Reilly (Practical C++ Programming 2nd edition) and I have a question. They have this code in a class fixed_pt on page 329

They both return (*this) and I don't know why one returns a fixed_pt object and the other returns a reference to a fixed_pt object. :confused:
 

JetBlack69

Diamond Member
Sep 16, 2001
4,580
1
0
Thanks for the response BingBongWongFooey. I'm coming from a Java background so I'm a little confused. What is the difference between returning an object and returning a reference to an object? I'm not sure when each should be done. :confused:
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Well by default (in C and in C++), everything is passed by copying. Unless you specifically use a pointer (c-style, not used as much in modern-style c++), or a reference, then the object will be copied. So returning a non-reference fixed_pt is returning a copy. In Java, I believe everything passes by reference.

An example:
 

JetBlack69

Diamond Member
Sep 16, 2001
4,580
1
0
Thanks for the reply BingBongWongFooey. I think I get it, so if I don't want a copy of an object, I should use a reference. I guess that is similar to pass-by-reference, but instead it's return-by-reference.

Thanks for your help. :)
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Originally posted by: JetBlack69
Thanks for the reply BingBongWongFooey. I think I get it, so if I don't want a copy of an object, I should use a reference. I guess that is similar to pass-by-reference, but instead it's return-by-reference.

Thanks for your help. :)

Yeah, references work the same way, whether returning or passing them. Usually for small stuff like ints, you just copy it, but for anything but a very small object, you will want to use references. (const when you just need to read it)
 

JetBlack69

Diamond Member
Sep 16, 2001
4,580
1
0
Ok, I just read that returning the self reference is good so you can do cascading assignments like:

object obj("cool");
object a, b, c,;
a = b = c = obj;

If it didn't return a reference, then it would use copies and they would get destroyed?
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Well it'd mostly work out the same either way in the case of operator=, but if the object is really big, then all that copying would be pretty wasteful. Also, say you did this:

void modify(object& o)
{
// ... do something
}

object a("hello");
object b, c;

modify(b = a);

Then modify() would be modifying a copy which would then get thrown away. If operator= returned a reference, then 'b' would be modified permanently by modify(). But that's kind of a stupid example. :p

Here's something I found on google (the non-cache page whines at you to register for something or another)