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?
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.
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.
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.
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.
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:
In this case it appears only the second point applies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With