Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good to have all the setter functions return a reference to the object in c++?

Is it good to have all the setter functions return a reference to the object in c++?

like image 499
yesraaj Avatar asked Apr 15 '09 17:04

yesraaj


People also ask

What should a setter return?

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.

Should a getter return a reference?

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.

When should I return by reference?

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.

Should you return a reference C++?

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.


1 Answers

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...

like image 70
Eclipse Avatar answered Sep 29 '22 08:09

Eclipse