1

Is there any problem with declaring a class with a static member which is another class in a header. E.g:

class Stat
{
public:
    int avar;
    Stat();
};

class Test
{
public:
    static Stat stat;
};

The reason I fear it might cause problems is that it seems very similar to declaring a global variable in a header. If included in two cpp files the global gets declared in both files leading to an error.

'stat' in the example above still needs to be created only once between two cpp files the same as a global so how can the compiler handle the one situation but not the other or is the answer that it can't?

user393956
  • 21
  • 2
  • 1
    These are __class definitions, not declarations__. `Test::stat`, howver, is just a __member declaration__ and still needs a definition. (See [this answer](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration/1410632#1410632) for what are declarations and definitions in C++.) – sbi Jul 21 '10 at 11:18

2 Answers2

4

You are only declaring a static class member variable in the class itself, you have to define it separately in a cpp file:

Stat Test::stat;

So there are no compiler or linker errors. Declaration in your header simply refers to the definition in the cpp file.

In global variable terms, the declaration is equivalent to:

extern int global;

And the definition is equivalent to:

int global;
Alex B
  • 75,980
  • 39
  • 193
  • 271
4

The answer is that you are DECLARING the static (like you can DECLARE a global). But you should only DEFINE it in cpp files.

in a .h :

extern int myGlobal;
class A
{
  static int myStaticMember;
};

in a .cpp :

int myGlobal = 42;
int A::myStaticMember = 42;
Scharron
  • 15,365
  • 6
  • 40
  • 63