Click to See Complete Forum and Search --> : cpp - int & function() question
tecknophreak
08-27-2002, 10:09 AM
i'm working with some cpp and i ran across a function such as:
int & function() { return x };
what does this do? it doesn't seem to work like
function(int &x)
it seems the same as
int function() { return x }
bwkaz
08-27-2002, 11:45 AM
I'm guessing that x is a private member of a class that function() is a public member of?
The reason it's returned as a reference is so that after the call, you can change x:
int & my_x = object.function();
my_x = 75;
cout << object.function();This should print 75.
tecknophreak
08-27-2002, 12:06 PM
well, that seems to be it. although i'm not sure what this guy's doing. he's using it to reference a member of a structure. i can't seem to understand the benefit, with exception that it'll make the line(code) shorter
bwkaz
08-27-2002, 12:41 PM
Yeah, I wouldn't think there would be very many places where it'd be useful -- normally, you'd have a "getter" function that returned a copy, and a "setter" function that took whatever and set the member to that. Whatever... at least you know what it does...
Energon
08-27-2002, 08:31 PM
Actually, what you'd do is return a constant reference. Returning copies is bad unless it's a primitive type. Returning a constant reference says "I'm giving you a reference, but you can't modify the data", which is what you want. If they try putting it into a non-constant variable, it'll make the copy instead.
The general rule of thumb is that if you want to allow modification, use a pointer, if you don't, use a constant reference. If it's a primitive type that you don't want modified, just return a copy. That "rule" goes for both returning values and passing values to a function.
bwkaz
08-27-2002, 09:54 PM
Yeah, but these are int's... ;)
Actually, you're right, and no, I wasn't thinking that far. It's just a coincidence that this example was a primitive.