"Often, however, a class needs functions for internal processing that
should not be called by code outside the class. Such functions should be made private."
I just need some help understanding the core of the purpose behind private member functions.
This is the example program they used to explain private member functions.
// This program uses a private Boolean function to determine if
// a new value sent to it is the largest value received so far.
#include <iostream>
usingnamespace std;
class SimpleStat
{
private:
int largest; // The largest number received so far
int sum; // The sum of the numbers received
int count; // How many numbers have been received
bool isNewLargest(int);
public:
SimpleStat(); // Default constructor
bool addNumber(int);
double getAverage();
int getLargest()
{ return largest; }
int getCount()
{ return count; }
};
// SimpleStat Class Implementation Code
SimpleStat::SimpleStat()
{
largest = sum = count = 0;
}
bool SimpleStat::addNumber(int num)
{ bool goodNum = true;
if (num >= 0) // If num is valid
{
sum += num; // Add it to the sum
count++; // Count it
if (isNewLargest(num)) // Find out if it is
largest = num; // the new largest
}
else // num is invalid
goodNum = false;
return goodNum;
}
bool SimpleStat::isNewLargest(int num)
{
if (num > largest)
returntrue;
elsereturnfalse;
}
double SimpleStat::getAverage()
{
if (count > 0)
returnstatic_cast<double>(sum) / count;
elsereturn 0;
}
// Client Program
int main()
{
int num;
SimpleStat statHelper;
cout << "Please enter the set of non-negative integer \n";
cout << "values you want to average. Separate them with \n";
cout << "spaces and enter -1 after the last value. \n\n";
cin >> num;
while (num >= 0)
{
statHelper.addNumber(num);
cin >> num;
}
cout << "\nYou entered " << statHelper.getCount() << " values. \n";
cout << "The largest value was " << statHelper.getLargest() << endl;
cout << "The average value was " << statHelper.getAverage() << endl;
system("pause");
return 0;
}
When you use a car, you press a pedal and turn the driving wheel. You don't need to, nor even want to know how pressing the pedal makes the car move.
Public methods are the interface of the class. How it is used.
Private methods are part of the implementation that gets the job done under the hood. They are nobody else's business.
Why use additional methods rather than having it all in the public methods? For the same reason why functions are used in other contexts too: to organize code and reduce repetition.