[CSI] Accessor Functions- why not Private: ?

Mikhail Nesterenko mikhail at cs.kent.edu
Sat Jul 24 21:21:50 EDT 2021


> 
> You may have mentioned this in the Lecter on Friday, but why are
> accessor functions not set to be private since they only access
> member variables of a Class? I understand why they are declared as
> const, but why not restrict their use further in the class
> definition?
> 

Private members, functions or variables, may only be invoked in other
member functions of the same class.

For example, in the below case, getDay() is declared private. It may
only be invoked inside other member functions: set() and getMonth(),
but not inside main(). This limits its usefulness.

class Date {
public:
   void set(int, int, int); 
   int getMonth() const {return month_;} 
private:
   int getDay() const {return day_;} // private accesor
   int month_;
   int day_;
   int year_;
};

int main(){

    Date today;
    today.set(1,2,3); // may be invoked since it is public
    cout << today.getMonth(); // may be invoked 

    cout << today.getDay(); // ERROR, may NOT be invoked since
                            // declared private
}

In general, member functions are seldom declared private. Such
functions, called "helper functions", are just "helping" with the
implementation of the other member function of the same class but
cannot be used by other parts of the program.

Thanks,
--
Mikhail


More information about the cs13001 mailing list