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?

1
  • 1
    These are class definitions, not declarations. Test::stat, howver, is just a member declaration and still needs a definition. (See this answer for what are declarations and definitions in C++.) Commented Jul 21, 2010 at 11:18

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

I think you meant A::myStaticMember
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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.