Can I combine setter and getter in one method, in C ++?

I would like to combine setter / getter in one C ++ method to be able to do the following:

Foo f;
f.name("Smith");
BOOST_CHECK_EQUAL("Smith", f.name());

I don’t know how to declare such a method inside the class Foo:

class Foo {
public:
  // how to set default value??
  const string& name(const string& n /* = ??? */) {
    if (false /* is it a new value? */) {
      _name = n;
    }
    return _name;
  }
private:
  string _name;
}

I am looking for some elegant solution with true C ++ spirit :) Thank you!

+3
source share
3 answers
class Foo {
public:

  const string& name() const {
    return name_;
  }

  void name(const string& value) {
    name_ = value;
  }

private:
  string name_;
};
+6
source

You can create a second method with different parameters, in this case no one will simulate the default parameter:

string& name() {
    // This may be bad design as it makes it difficult to maintain an invariant if needed...
    // h/t Matthieu M., give him +1 below.
    return _name;
}

And if you need a const getter, just add it!

const string& name() const {
    return _name;
}

The compiler will know which one to call that magic overload.

Foo f;
f.name("Smith"); // Calls setter.
BOOST_CHECK_EQUAL("Smith", f.name()); // Calls non-const getter.
const Foo cf;
BOOST_CHECK_EQUAL("", cf.name()); // Calls const getter.
+3
source

I would not advise doing this because then you cannot make your const get functions. This will work, but it will break completely if someone has const Foo and wants to execute GetA (). For this reason, I recommend separate functions and const GetA ().

class Foo
{
   int _a;
   static int _null;
public:
   const int& a(const int& value = _null) {
      if (&value != &_null)
         _a = value;

      return _a;
   }
};
+1
source

Source: https://habr.com/ru/post/1753240/


All Articles