• C++ - Static Globals/Static Private Members?
    2 replies, posted
Hey there. Now, I know that "static" in a C++ class means that the var you're declaring can be accessed in a similar fashion to a namespace, e.g [code]class MyTest { public: static int test = 5; }; int main() { std::cout << MyTest::test; }[/code] However, there are two other uses I've seen with 'static' that don't really make sense, at least with my current understanding. 1. The use of a global static, e.g [code]static int somerandomvar = 2; int main() { std::cout << "wat?"; }[/code] 2. The use of a static private member in a class/struct. [code]struct test { private: static int test = 5; };[/code] What do both of these uses of it mean?
[QUOTE=MaximLaHaxim;49619427] 1. The use of a global static, e.g [code]static int somerandomvar = 2; int main() { std::cout << "wat?"; }[/code][/QUOTE] 'static' makes sure the variable is only valid for the cpp it was defined in. For a non-static global variable, you can do stuff like: main.cpp: [code] int somerandomvar = 2; void print_some_random_var(); int main(int,char*[]) { print_some_random_var(); for(;;); return EXIT_SUCCESS; } [/code] other.cpp: [code] #include <iostream> extern int somerandomvar; void print_some_random_var() { std::cout<<somerandomvar<<std::endl; } [/code] This would print '2'. If 'somerandomvar' is static, however, you'll get an unresolved external, because it can't find the source for 'somerandomvar' in 'other.cpp'. Basically, non-static global variables can be shared between cpps, static global variables can't. [QUOTE=MaximLaHaxim;49619427]2. The use of a static private member in a class/struct. [code]struct test { private: static int test = 5; };[/code][/QUOTE] You could use it for example to keep track of the number of objects that exist of your class at any time: [code]#include <iostream> class MyTest { private: static int COUNT; public: MyTest(); ~MyTest(); }; int MyTest::COUNT = 0; MyTest::MyTest() { ++COUNT; std::cout<<"There are "<<COUNT<<" objects of type '"<<typeid(*this).name()<<"'"<<std::endl; } MyTest::~MyTest() { --COUNT; } int main(int,char*[]) { MyTest a,b,c,d,e,f; for(;;); return EXIT_SUCCESS; }[/code] This is pretty much the only case I can think of where I've used a static private, but I'm sure there are others.
Sorry, you need to Log In to post a reply to this thread.