which style of member-access is preferable
- by itwasntpete
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