class foo
{
int val;
public:
int val() const { return val; } // get val
int& val() { return val; } // modify val
};
int main()
{
foo f;
foo.val() = 20; // <-- different paradigm than I'm used to
}
I've almost always done something like foo.setVal(20). Saw some code doing it the other way and I was intrigued.
What's everyone's opinion on the former paradigm?
As has been mentioned... returning a nonconst reference to the variable defeats the entire point of having getters/setters. At that point you might as well just make the variable public.
I was browsing an open source project and found some code bits that used that design idiom and I wasn't sure what to think of it. I originally had the same general opinion as all of you, but I needed something to back that up.