Is it good to have all the setter functions return a reference to the object in c++?
Setters cannot return values. While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.
Because the getter method returns the reference of the internal variable scores directly, the outside code can obtain this reference and make a change to the internal object. So the rule of thumb is: Do not return a reference of the original object in the getter method.
You should return a reference to an existing object that isn't going away immediately, and where you don't intend any transfer of ownership.
A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.
It's a usable enough pattern if there's a lot of things that need to be set on an object.
class Foo
{
int x, y, z;
public:
Foo &SetX(int x_) { x = x_; return *this; }
Foo &SetY(int y_) { y = y_; return *this; }
Foo &SetZ(int z_) { z = z_; return *this; }
};
int main()
{
Foo foo;
foo.SetX(1).SetY(2).SetZ(3);
}
This pattern replaces a constructor that takes three ints:
int main()
{
Foo foo(1, 2, 3); // Less self-explanatory than the above version.
}
It's useful if you have a number of values that don't always need to be set.
For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite.
Of course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With