Search code examples
c++encapsulationgetter-settergetterprivate-members

Why do people write private-field getters returning a non-const reference?


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?


Solution

  • There's a recurring mantra, that getter/setter functions should be used to encapsulate your data. Hence many (unexperienced or coffee-overloaded) programmers get the idea they should use something like:

    int& integer() { return integer_; }
    

    but that isn't much different from simply writing:

    class foo {
    public: // <<<
        int integer_;
        string someString_;
        // ...
    };
    

    Well, it adds a function call, but you cannot control what the client does with the reference.


    If you really want to provide a getter function write:

    const int& integer() const { return integer_; }
    

    A corresponding setter function looks like:

    void integer(const int& value) {
        integer_ = value;
    }