When/why to make function private in class?

I usually make the helper functions private. But what is helper seems to be vague. So let me give you an example. Suppose you've the following class Sample; it exposes few public functions, one of them, say, is DoWork(). This function takes one parameter. But it doesn't assume that the parameter will always be valid, so it first checks the validity of parameter for which it has lots of code in the beginning of the function. Something like this:

class Sample
{
   public:
      void DoWork(SomeClass param)
      {
               /*
                *lots of code related to validation of param
                */  

                //actual code that operates on the param 
                //and other member data IF the param is valid
      }
};

Since you've written lots of code related to validation of the param, it makes the function cumbersome, and difficult to read. So you decided to move this validation code to function say, IsValidParam(), and then you call this function from DoWork() passing the parameter param to it. Something like this:

class Sample
{
   public:
      void DoWork(SomeClass param)
      {       
            if ( IsValidParam(param))       
            {
                //actual code that operates on the param 
                //and other member data IF the param is valid
            }
      }
};

That looks cleaner, right?

Okay, you've written IsValidParam() somewhere in the class, but the question you face now is, would you make this function public? If this function is used only by your other functions like DoWork(), then making IsValidParam() public doesn't make sense. So you decided to make this function private.

class Sample
{
   public:
      void DoWork(SomeClass param)
      {       
            if ( IsValidParam(param))       
            {
                //actual code that operates on the param 
                //and other member data IF the param is valid
            }
      }
  private:
      bool IsValidParam(SomeClass param)
      {
          //check the validity of param.
          //return true if valid, else false.
      }
};

Functions of this kind (IsValidParam) should be private. I call these functions helper functions.

Hope this explanation helps you!


You should make a function private when you don't need other objects or classes to access the function, when you'll be invoking it from within the class.

Stick to the principle of least privilege, only allow access to variables/functions that are absolutely necessary. Anything that doesn't fit this criteria should be private.