Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

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

I don't know how can I declare such a method inside Foo class:

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'm looking for some elegant solution, with a true C++ spirit :) Thanks!

like image 616
yegor256 Avatar asked Oct 17 '25 21:10

yegor256


2 Answers

class Foo {
public:

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

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

private:
  string name_;
};
like image 64
Bertrand Marron Avatar answered Oct 20 '25 11:10

Bertrand Marron


You can create a second method with different parameters, in this case none to simulate a 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 as well!

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

The compiler will know which one to call, that's the magic of overloading.

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.

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!