tags:

views:

158

answers:

3

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!

+3  A: 

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.
squelart
This is called *overloading*.
Nikolai N Fetissov
Shirik
@Shirik: This solution does what Vincenzo needs, by separating the getter and setter, though they have the same name. But you're correct that the first non-const getter could return a non-const reference to the string, I'll fix it, thanks.
squelart
@squelart: It's not that it "could" return a non-const reference to the string, it *must* return a non-const reference, or else it will be useless (there would be no "setter" part). However, with the fix, it works.
Shirik
Argh! First lesson of design: never ever return a handle to your internals. This annihilates any chance of ever maintaining a class invariant including this attribute.
Matthieu M.
+1  A: 

I would not advise trying to do this, because then you can't make your "get" functions const. This would work, but it would totally break when someone has a const Foo and wants to execute GetA(). For that reason, I advise separate functions and a const GetA().

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

      return _a;
   }
};
Shirik
+6  A: 
class Foo {
public:

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

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

private:
  string name_;
};
Bertrand Marron
Be wary of the `_`, even though it seems okay here, the standard forbid a number of identifiers with underscores. From the top of my head: any identifier with a double underscore and any identifier beginning by an underscore followed by an uppercase letter... but I may be forgetting some.
Matthieu M.
That is true. I was just reusing the OP's variables' names. I usually prefer the `name_` syntax.
Bertrand Marron