Accessors and Mutators in C++

October 2016

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.

Accessor and Mutator Functions

Accessors are member functions that allow access to data members. Member functions that allow for modification of the data members are called mutators.

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:

1) The accessor must have the same type as the returned variable.

2) The accessor does not need not have arguments.

3) 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 for editing of the contents of a protected data member. For a mutator to accomplish its function, the following conditions must be present:

1) 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.

2) The mutator does not need to return a value.

3) 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;

}



Original document published on CommentcaMarche.net.

Related :

This document entitled « Accessors and Mutators in C++ » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.