Accesor and Mutator

Here is the example that is in question

* Only member functions of a class are allowed to access the private data fields of objects of that class.
1
2
3
4
          void raise_salary(Employee& e, double percent)
          {
             e.salary = e.salary * (1 + percent / 100 ); /* Error */
          }


* Data fields must be accessed by accessor and mutator functions.
1
2
3
4
5
          void raise_salary(Emplyee & e, double percent)
          {
             double new_salary = e.get_salary() * (1 + percent / 100);
             e.set_salary(new_salary);
          }


I know this example is correct , but I am still not understanding exactly why the first one is not allowed. Why doesn't C++ compiler let you modify the data with "=" here? Please give me an explanation as long as possible.

Thank you so much.

Here is also the class construction:

#include "ccc_empl.h"

Employee::Employee()
{
salary = 0;
}

Employee::Employee(string employee_name, double initial_salary)
{
name = employee_name;
salary = initial_salary;
}

void Employee::set_salary(double new_salary)
{
salary = new_salary;
}

double Employee::get_salary() const
{
return salary;
}

string Employee::get_name() const
{
return name;
}
Last edited on
That's the whole point of having private members. They're only accessible to other members. If there's no significative invariant to keep track, there's really no need to make data private. Typically, you'd use setter functions to make sure no invalid data can be passed (like a negative number for salary, for instance).
Topic archived. No new replies allowed.