One of the characteristics of C++, which is an object-oriented programming language, is the concept of encapsulation. With encapsulation, a programmer defines labels for the data members and functions and specifies whether they are accessible by other classes. When the programmer labels data members "private," they cannot be accessed and manipulated by member functions of other classes. Accessors allow access to these private data members.
An accessor function in C++ and the mutator function are like the set and get functions in C#. They are used instead of making a class member variable public and changing it directly within an object. To access a private object member, an accessor function must be called.
Typically for a member such as Level, a function GetLevel() returns the value of Level and SetLevel() to assign it a value.
Characteristics of an Accessor Function
- An accessor doesn't need arguments
- An accessor has the same type as the retrieved variable
- The name of the accessor begins with the Get prefix
- A naming convention is necessary
While an accessor function makes a data member accessible, it does not make it editable. Modification of a protected data member requires a mutator function.
Because they provide direct access to protected data, mutator and accessor functions must be written and used carefully.