Hey Guys
Is it possible to access to access and use static members within a class without first creating a instance of that class? Ie treat the the class as some sort of dumping ground for globals
James
Hey Guys
Is it possible to access to access and use static members within a class without first creating a instance of that class? Ie treat the the class as some sort of dumping ground for globals
James
Yes:
class mytoolbox
{
public:
static void fun1()
{
//
}
static void fun2()
{
//
}
static int number = 0;
};
...
int main()
{
mytoolbox::fun1();
mytoolbox::number = 3;
...
}
Yes, it's precisely what static
means for class members:
struct Foo {
static int x;
};
int Foo::x;
int main() {
Foo::x = 123;
}
In short, yes.
In long, a static member can be called anywhere, you simply treat the class name as a namespace.
class Something
{
static int a;
};
// Somewhere in the code
cout << Something::a;
You can also call a static method through a null pointer. The code below will work but please don't use it:)
struct Foo
{
static int boo() { return 2; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo* pFoo = NULL;
int b = pFoo->boo(); // b will now have the value 2
return 0;
}
On the other hand, that's what namespace are for:
namespace toolbox
{
void fun1();
void fun2();
}
The only use of classes of static functions is for policy classes.