Executive summary: Static variables declared in a class in C++ get set up even if there is not a single object of the given class.
Request: Please let me know if there are errors (logical, typographical, or otherwise) in this document.
Request: Please let me know if there are errors (logical, typographical, or otherwise) in this document.
Microsoft has this to say about a static variable:
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope.
Here is our code for CBase.h
#ifndef CBASE_H_
#define CBASE_H_
class CBase
{
public:
static int x;
};
int CBase::x = 1987;
#endif // !CBASE_H_
Here is our code for Source.cpp where we have our main method:
#include#include #include "CBase.h" int main() { std::cout << CBase::x << std::endl; return 0; }
Now, let's talk about it for a minute. When, in the run time, do we access anything in the file CBase.h? The answer as far as I know is never. There is only one explanation (that I can think of) is that the integer x gets created during compile time.