suggest change

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;

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

    void some_func() {

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.]

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents