tags:

views:

130

answers:

2

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?

+4  A: 

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
+4  A: 

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
I think you meant `A::myStaticMember`
Gianluca
Thanks, edited.
Scharron