What are Accessors and Mutators in C++
One of the most critical aspects of object-oriented programming is encapsulation, which allows one to define labels for the data members and member functions, to specify if they are accessible from other classes or not. As a result, data members labeled as private can not be directly manipulated by member functions of other classes. In order to be able to manipulate these data members, the creator of the class must provide special member functions labeled as public.
What are Accessors and Mutators used for?
Accessors and Mutators are used in object-oriented programming to deliver access to private variables of the object. These methods are also called getter and setter since they help get and set the object's private variables.
What is an Accessor?
An accessor is a member function that allows someone to retrieve the contents of a protected data member. For an accessor to perform its function, the following conditions must be met:
- The accessor must have the same type as the returned variable.
- The accessor does not need not have arguments.
- A naming convention must exist, and the name of the accessor must begin with the "Get" prefix.
The syntax of an accessor reduced to its simplest expression looks like this:
class MaClasse{ private : TypeDeMaVariable MaVariable; public : TypeDeMaVariable GetMaVariable(); }; TypeDeMaVariable MaClasse::GetMaVariable(){ return MaVariable; }
In the above example, the accessor of the data member could be the following:
class Toto{ private : int age; public : int GetAge(); }; int Toto::GetAge(){ return age; }
What is a Mutator?
A mutator is a member function that allows editing of the contents of a protected data member. For a mutator to accomplish its function, the following conditions must be present:
- As a parameter, it must have the value to be assigned to the data member. The parameter must be of the same type as the data member.
- The mutator does not need to return a value.
- A naming convention must exist, with the name of the accessor beginning with the "Set" prefix.
The syntax of a mutator reduced to its simplest expression looks like this:
class MaClasse{ private : TypeDeMaVariable MaVariable; public : void SetMaVariable(TypeDeMaVariable); }; MaClasse::SetMaVariable(TypeDeMaVariable MaValeur){ MaVariable = MaValeur; }
In the above example, the mutator of data member could be the following:
class Toto{ private : int _age; public : void SetAge(int); }; void Toto::SetAge(int age){ _age = age; }