Characteristics of Accessor Functions in C++

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

Software developing team working in the office
AlexSava / Getty Images

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.

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.

mla apa chicago
Your Citation
Bolton, David. "Characteristics of Accessor Functions in C++." ThoughtCo, Feb. 16, 2021, Bolton, David. (2021, February 16). Characteristics of Accessor Functions in C++. Retrieved from Bolton, David. "Characteristics of Accessor Functions in C++." ThoughtCo. (accessed May 29, 2023).