Hello,
Why should i use static function and static members?What is their real usage?
Please help me.
Thanx in advance,
John.
This is a discussion on The Real use of static within the C++ Programming forums, part of the General Programming Boards category; Hello, Why should i use static function and static members?What is their real usage? Please help me. Thanx in advance, ...
Hello,
Why should i use static function and static members?What is their real usage?
Please help me.
Thanx in advance,
John.
codeffects software solutions
A workaround globals![]()
Woop?
> A workaround globals
Yep. Plus unlike regular globals, you have some idea as to what the global is used for fairly quickly. Its parallel to using namespaces to keeping order among your global variables.
>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:
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> 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; }
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.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; }
My best code is written with the delete key.
Also you can use static member function without instancing the class, to they are great if you want to control the access to the constructor, or just put a few related functions together in an elegant way.