- mutator - Function that modifies a class' data members
// Mutator SetName() is modifying name data member
void Student::SetName(string stuname)
{
name = stuname;
}
- accessor - Function that accesses (but does not modify) a class' data members
// Accessor GetName() is only accessing (not changing) name data member
string Student::GetName()
{
return name;
}
- Usually every class data member has a setter function (mutator) for setting the data member
and a getter function (accessor) for getting the data member value
- Accessor functions usually have
const
next to the function declaration to
make the compiler ensure the function does not modify any data memebers
- An accessor function can only call other accessor functions
- Example that separates member function declarations and definitions
class Student
{
public:
void SetName(string stuname); // Mutator (setter)
string GetName() const; // Accessor (getter)
void SetGpa(double stugpa); // Mutator (setter)
double GetGpa() const; // Accessor (getter)
void Print() const; // Accessor
private:
string name;
double gpa;
};
// Definitions
void Student::SetName(string stuname)
{
name = stuname;
}
string Student::GetName() const
{
return name;
}
void Student::SetGpa(double stugpa)
{
gpa = stugpa;
}
double Student::GetGpa() const
{
return gpa;
}
void Student::Print() const
{
cout << "Name: " << name << "\nGPA: " << gpa << endl;
}