0

How to define a static member in case there is not header file ?

The code:

class MyClass
{
};

int MyClass::staticMember;  // Error: class MyClass has no member staticMember!

Any help?

Homam
  • 23,263
  • 32
  • 111
  • 187
  • 1
    You just declare it wherever your class declaration is. Doesn't matter if it's in a header file or not. – Jon Apr 28 '11 at 22:56
  • @Jon :Can't I not have a class declaration ? – Homam Apr 28 '11 at 22:57
  • @Jack: Not if you want the class to exist. Are you trying to use it in a manner more suited to a `namespace`? – Jon Apr 28 '11 at 22:58
  • 1
    Remember: "header" != "[declaration](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration/1410632#1410632)" – sbi Apr 28 '11 at 23:02

2 Answers2

6

This will work:

//
// Inside .cpp file
//
class MyClass
{
    static int staticMember;
};

int MyClass::staticMember;
StackedCrooked
  • 34,653
  • 44
  • 154
  • 278
  • Probably want `staticMember` to be declared `public` or have accessors. Indeed, the desire for accessors would be the main reason to use a `class` here rather than a named or un-named `namespace`. – Keith Apr 29 '11 at 00:52
2

If it's not in the class declaration, you can't define it.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836