C++ Non-Static Member Functions Encapsulation


Example

A common use of member functions is for encapsulation, using an accessor (commonly known as a getter) and a mutator (commonly known as a setter) instead of accessing fields directly.

class Encapsulator {
    int encapsulated;

  public:
    int  get_encapsulated() const { return encapsulated; }
    void set_encapsulated(int e)  { encapsulated = e; }

    void some_func() {
        do_something_with(encapsulated);
    }
};

Inside the class, encapsulated can be freely accessed by any non-static member function; outside the class, access to it is regulated by member functions, using get_encapsulated() to read it and set_encapsulated() to modify it. This prevents unintentional modifications to the variable, as separate functions are used to read and write it. [There are many discussions on whether getters and setters provide or break encapsulation, with good arguments for both claims; such heated debate is outside the scope of this example.]