title: How to write C++ getters and setters
body: <p>If I need to write a setter and/or getter for I write it like this:</p>
  <pre><code>struct X { /*...*/};
  
  class Foo
  {
  private:
      X x_;
  
  public:
      void set_x(X value)
      {
          x_ = value;
      }
      X get_x()
      {
          return x_;
      }
  };
  </code></pre>
  <p>However I have heard that this is the <em>Java style</em> of writing setters and getters and that I should write it in C++ style. Moreover I was told it is ineficient and even incorrect. What does that mean? How can I write the setters and getters in C++?</p>
  <hr />
  <p><strong>Assume the need for getters and/or setters is justified</strong>. E.g. maybe we do some checks in the setter, or maybe we write only the getter.</p>
  <p>There has been a lot of chatter about not needing getters and setters. While I agree with most of what's been said here, I still avocate for the need to know how to idiomatically write such methods because there are legitimate reasons where getters and setters are the right solution. They might not look at first glance as a setter or getter but they are, or at least the pattern for writing them applies.</p>
  <p>E.g.:</p>
  <ul>
  <li><p>Getting the size of a vector. You don't want to expose a data member, because it needs to be read only.</p>
  </li>
  <li><p>Getters and setters don't need to just expose a data member. Think about getting and setting an element of an array. There is logic there, you can't just expose a data member, there is no data member to expose in the first place. It's still a getter/setter pair you can't avoid:</p>
  <pre><code>class Vector
  {
      void set_element(std::size_t index, int new_value);
      int get_element(std::size_t index);
  };
  </code></pre>
  <p>Knowing the C++ idiomatic way of writing getters and setters will allow me to write the above <code>get_element</code>/<code>set_element</code> in a C++ idiomatic way.</p>
  </li>
  </ul>