views:

148

answers:

5

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

A: 

Yes:

class mytoolbox
{
public:
  static void fun1()
  {
    //
  }

  static void fun2()
  {
    //
  }
  static int number = 0;
};
...
int main()
{
  mytoolbox::fun1();
  mytoolbox::number = 3;
  ...
}
AraK
+3  A: 

Yes, it's precisely what static means for class members:

struct Foo {
    static int x;
};

int Foo::x;

int main() {
    Foo::x = 123;
}
Pavel Minaev
Also, see http://www.acm.org/crossroads/xrds2-4/ovp.html#SECTION00040000000000000000 for some fun reading on static data in C++.
Nate Kohl
+2  A: 

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;
Oz
You can treat the class name as a namespace only in the context of the syntax not in any other way.
Martin York
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;
}
chollida
Technically, this is undefined behavior. You cannot deference a null pointer for any reason. The only things that you can do with a null pointer is a) assign another pointer to it and b) compare it with another pointer.
KeithB
+2  A: 

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.

Matthieu M.