C++ getters/setters coding style

Alex picture Alex · Apr 17, 2009 · Viewed 175.1k times · Source

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.

Answer

j_random_hacker picture j_random_hacker · Apr 17, 2009

Using a getter method is a better design choice for a long-lived class as it allows you to replace the getter method with something more complicated in the future. Although this seems less likely to be needed for a const value, the cost is low and the possible benefits are large.

As an aside, in C++, it's an especially good idea to give both the getter and setter for a member the same name, since in the future you can then actually change the the pair of methods:

class Foo {
public:
    std::string const& name() const;          // Getter
    void name(std::string const& newName);    // Setter
    ...
};

Into a single, public member variable that defines an operator()() for each:

// This class encapsulates a fancier type of name
class fancy_name {
public:
    // Getter
    std::string const& operator()() const {
        return _compute_fancy_name();    // Does some internal work
    }

    // Setter
    void operator()(std::string const& newName) {
        _set_fancy_name(newName);        // Does some internal work
    }
    ...
};

class Foo {
public:
    fancy_name name;
    ...
};

The client code will need to be recompiled of course, but no syntax changes are required! Obviously, this transformation works just as well for const values, in which only a getter is needed.