>Why should i use static function and static members?What is their real usage?
Sometimes it just doesn't make sense for every object to have a local copy of a data member. Take an object counter for example:
Code:
#include <iostream>
using namespace std;
class test {
static int class_n;
public:
test() { cout<<"There are "<< ++class_n <<" objects active"<<endl; }
~test() { cout<<"There are "<< --class_n <<" objects active"<<endl; }
};
int test::class_n = 0;
int main()
{
test a, b, c;
}
Such a thing is common and useful, but it would be ugly and unsafe without static members. The same goes for static member functions. There are times when it doesn't make sense to define an object just to call a member function if the function doesn't really need the object to exist. Take a default value for example:
Code:
#include <iostream>
#include <string>
using namespace std;
class test {
static string default_path;
string path;
public:
test(string init = default_path): path(default_path) {}
static void set_default_path(string init);
string get_path() const { return path; }
};
string test::default_path = "/my/stuff/";
void test::set_default_path(string init)
{
default_path = init;
}
int main()
{
test a;
cout<< a.get_path() <<endl;
// But wait! What if we're using Windows?
test::set_default_path("C:\\my\\stuff\\");
test b;
cout<< b.get_path() <<endl;
}
Sure, you could change the default path every time you create a new object, but this would be terribly annoying for clients who don't use a Unix style directory tree. So the static member function changes the default path class-wide. After calling it, any new objects will use the new default without needing to do anything special.