We can all agree on public variables being bad for encapsulation and all that. However, I noticed a lot of code that does this type of stuff:
class foo {
private:
int integer_;
string someString_;
// other variables
public:
int& integer() { return integer_; }
string& someString() { return someString_; }
// other "functions"
}
int main() {
foo f;
f.integer() = 10;
f.someString() = "something";
return 0;
}
I have seen this being used in many places and I don't get why. Basically it returns a reference to the data and thus exposes it directly to the outside. So encapsulation is not really achieved, not from any perspective.
Why is this commonly used?
(?<!const\s+(?:\w+\s+)?|::)\b\w+(?:::\w+)*\s*(?:<[^<>]*>\s*)*&\s+\w+(?:::\w+)*\s*\(
— May be not perfect, someone can suggest improvements! – Honorary