advantage of static member function

Hi,
Could anyone tell me what is advantage of static member function.why we need static member function when we have normal function....

static member functions don't have an implicit "this" pointer as the first parameter.

If a class member function does not access any members of the class (ie, the function is
declared inside the class entirely for containment purposes), then it can be declared static,
which means the function can be called without an instance of the class.

Example:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

class my_string {
   public:
       static size_t max_length()
           { return 42; }
};

int main() {
    std::cout << "The largest string we can hold is " << my_string::max_length() << " characters." << std::endl;
}
Some times the semantics of a member function or a data member dictate that this member be shared among all the objects of its class. In such cases we declare those member as static. The scope of the static members is their class and they don't have a this associated with them. So they should be accessed as: ClassName::methodName(args).

For example, if you want to maintain a count of the number of instances that a particular class has, the data member corresponding to that count and the member function to return the value of that count would be static.

Topic archived. No new replies allowed.