Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of private static member functions?

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?

like image 426
rve Avatar asked Jun 22 '11 20:06

rve


People also ask

What is the use of private static?

Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.

What is the use of private member functions?

Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class.

What is the use of private static methods in C#?

A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

What is the advantage of static member function?

Static function: Advantage: it could be called without existing real object. Static member functions become useful when you want the class as a whole to have a function, instead of each individual object. With a static member function, you can then change static variable data.


1 Answers

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.

like image 137
Mark Ransom Avatar answered Oct 13 '22 07:10

Mark Ransom