Mutators, accessors, and private helpers

  1. Mutators and accessors
    1. mutator - Function that modifies a class' data members
      // Mutator SetName() is modifying name data member
      void Student::SetName(string stuname)
      {
      	name = stuname;
      }
      
    2. 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;
      }
      
    3. 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
    4. Accessor functions usually have const next to the function declaration to make the compiler ensure the function does not modify any data memebers
    5. An accessor function can only call other accessor functions
    6. 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;
      }
      
  2. Private helper functions
    1. private helper functions - Private member function that object user does not need access to
    2. Use public keyword to define public member functions, which indicate the operations can be performed on an object
    3. Use private keyword to define private data members, variables that public member functions can access but are inaccessible outside the class
    4. Example Student class
      class Student
      {
      	public:
      		
      	...
      		void SetGpa(double stugpa)
      		{
      			if (GpaValid(stugpa))
      				gpa = stugpa;
      			else
      				gpa = 0;
      		}
      
      	private:
      		string name;
      		double gpa;
      
      		// private helper function
      		bool GpaValid(double gpa) const;
      };  
      
      bool Student::GpaValid(double gpa) const
      {
      	return gpa >= 0 && gpa <= 4;
      }
      
    5. Only class member functions can call private functions
      Student stu;
      if (stu.ValidGpa(4.0))  // ERROR - ValidGpa() is private!
      {
      	// ...
      }