Search code examples
c++coding-stylegetter-setter

C++ getters/setters coding style


I have been programming in C# for a while and now I want to brush up on my C++ skills.

Having the class:

class Foo
{
    const std::string& name_;
    ...
};

What would be the best approach (I only want to allow read access to the name_ field):

  • use a getter method: inline const std::string& name() const { return name_; }
  • make the field public since it's a constant

Thanks.


Solution

  • It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.

    In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.

    I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.