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

5 Answers 5

6

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

struct Foo {
    static int x;
};

int Foo::x;

int main() {
    Foo::x = 123;
}
1
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.

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;
1
  • You can treat the class name as a namespace only in the context of the syntax not in any other way. Commented Oct 28, 2009 at 21:47
0

Yes:

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

  static void fun2()
  {
    //
  }
  static int number = 0;
};
...
int main()
{
  mytoolbox::fun1();
  mytoolbox::number = 3;
  ...
}
-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;
}
2
  • 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
    Commented Nov 30, 2009 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. Commented Mar 28, 2012 at 7:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.