What is the use of private static member functions?

rve picture rve · Jun 22, 2011 · Viewed 40.9k times · Source

I was looking at the request parser from the boost::asio example and I was wondering why the private member functions like is_char() are static? :

class request_parser
{
  ...
  private:
    static bool is_char(int c);
  ...
};

It is used in the function consume which is not a static function:

boost::tribool request_parser::consume(request& req, char input)
{
  switch (state_)
  {
    case method_start:
    if (!is_char(input) || is_ctl(input) || is_tspecial(input))
    {
      return false;
    }
    ...

Only member functions can call is_char() and no static member function is calling is_char(). So is there a reason why these functions are static?

Answer

Mark Ransom picture Mark Ransom · Jun 22, 2011

This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:

  1. It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function;
  2. It associates the function with the class in a similar way to a namespace.

In this case it appears only the second point applies.