Using static class members in a class is a common practice. consider the following definition:
foo.h
class foo
{
public:
virtual ~foo();
protected:
foo();
static foo ms_oFooStaticObject;
}
foo.cpp
foo foo::ms_oFooStaticObject;
foo::foo(){}
foo::~foo(){}
void main()
{
int i;
}
while compiling the above code there is no compiler error, and you can simply run in step mode and observe the static c-tor being executed.
how can this be? is this a compiler bug?
I am using visual studio 2005 (Professional Edition) with SP1 (SP.050727-7600)
@user797308: I assume you would have no problem if someone declared and defined a global variable named ms_oFooStaticObject. In other words, rather than defining
foo foo::ms_oFooStaticObject;definefoo ms_oFooStaticObject;(This would require the constructor was public, of course).Plain old vanilla global variables are declared via
extern <type> <global_name>;and defined using<type> <global_name>;(possibly with some initial value).Those static members in a class are really just global variables with the class name prepended in front of their names. The class definition is declaring them. Think of the declaration of ms_oFooStaticObject inside of class foo as being analogous to
extern foo ms_oFooStaticObject;. How about the definition of the variable? That’s what thatfoo foo::ms_oFooStaticObject;statement is doing.The comparison with globals is quite apt. There’s a lot of baggage associated with globals. It is a good idea to think of the static members of a class as having the same kinds of problems as do globals in general.
Edit
Nawaz’s response triggered a thought. user797308’s problem might be that
foo::ms_oFooStaticObjectitself is protected, so how can it be defined at file scope? The answer is that because the language requires those static data members to be defined at file scope, the language of course has to allow such definitions, even for static members that have non-public visibility.