which style of member-access is preferable

Posted by itwasntpete on Programmers See other posts from Programmers or by itwasntpete
Published on 2013-06-26T23:54:40Z Indexed on 2013/06/27 4:30 UTC
Read the original article Hit count: 281

Filed under:
|
|

the purpose of oop using classes is to encapsulate members from the outer space. i always read that accessing members should be done by methods. for example:

template<typename T>
class foo_1 {
  T state_;
public:
  // following below
};

the most common doing that by my professor was to have a get and set method.

  // variant 1
  T const& getState() { return state_; }
  void setState(T const& v) { state_ = v; }

or like this:

  // variant 2
  // in my opinion it is easier to read
  T const& state() { return state_; }
  void state(T const& v) { state_ = v; }

assume the state_ is a variable, which is checked periodically and there is no need to ensure the value (state) is consistent. Is there any disadvantage of accessing the state by reference? for example:

  // variant 3
  // do it by reference
  T& state() { return state_; }

or even directly, if I declare the variable as public.

template<typename T>
class foo {
public:
  // variant 4
  T state;
};

In variant 4 I could even ensure consistence by using c++11 atomic.

So my question is, which one should I prefer?, Is there any coding standard which would decline one of these pattern?

for some code see here

© Programmers or respective owner

Related posts about c++

Related posts about coding-style