Accessor Functions

An accessor function allows access to private data members in C++

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.

Accessor Function

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. For example:

class CLevel {
private:
int Level;
public:
int GetLevel() {return Level;} ;
     void SetLevel(int NewLevel) { Level=NewLevel;} ;
 
 };

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

Mutator Function

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. 
 

Format
mla apa chicago
Your Citation
Bolton, David. "Accessor Functions." ThoughtCo, Oct. 18, 2017, thoughtco.com/definition-of-accessor-958008. Bolton, David. (2017, October 18). Accessor Functions. Retrieved from https://www.thoughtco.com/definition-of-accessor-958008 Bolton, David. "Accessor Functions." ThoughtCo. https://www.thoughtco.com/definition-of-accessor-958008 (accessed November 18, 2017).