2

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

Dark Templer
  • 277
  • 5
  • 10

5 Answers5

6

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
  • 99,783
  • 25
  • 219
  • 289
  • Also, see http://www.acm.org/crossroads/xrds2-4/ovp.html#SECTION00040000000000000000 for some fun reading on static data in C++. – Nate Kohl Oct 28 '09 at 21:52
3

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.
  • 287,565
  • 48
  • 449
  • 722
2

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.
  • 5,299
  • 2
  • 23
  • 30
0

Yes:

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

  static void fun2()
  {
    //
  }
  static int number = 0;
};
...
int main()
{
  mytoolbox::fun1();
  mytoolbox::number = 3;
  ...
}
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
-1

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
  • 7,834
  • 11
  • 55
  • 85
  • 1
    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 Nov 30 '09 at 16:43
  • The this/pFoo pointer will dereferenced in case of accessing a member. static function do not access members and there are no members. Even non-virtual methods could be called via null-pointer without exception. they crash only when accessing members. Anyone should know and accept this in order to find some strange bugs. – stefan bachert Mar 28 '12 at 07:48