I have my entire program in the same .cpp file, so when you say in the .cpp file you mean anywhere in the main function? |
It is common to put a class definition in a header file and then the class implementation in the a code file. The code file includes the header file.
SecurityLog.h
1 2 3 4 5 6 7
|
// any includes needed by the class definition
class SecurityLog
{
.
.
};
|
SecurityLog.cpp
1 2 3
|
#include "SecurityLog.h"
// implementation of the class member functions.
|
Some compiliers use extensions other than .cpp for code files.
What is the difference between a normal int declaration and a static int declaration? |
For normal class member variables, whether public or private, each instantiated object has its own member variables, as you found above. When the member variables are declared as static the variables are unique and separate from any instantiated class, though they can still be accessed through any particular class object. All instantiated objects share the same static variables. This is why static variables cannot be initialized in the constructor, but need to be initialized separately. It is even possible to access the
public static members of a class without actually instantiating any class objects in the program. This is done through the class scope resolution operator. If in your
SecurityLog class
FailCount had been public, you could write:
1 2 3 4 5
|
int main()
{
std::cout << SecurityLog::FailCount << std::endl;
return 0;
}
|
This would output 3 even though no
SecurityLog objects are instantiated in the program.
By the way, the above is not an argument for making FailCount public but just to illustrate using the scope resolution operator to access public static member variables.
There is one exception to the rule that static member variables must be initialized outside the class definition. Static member variables of const integral type can be initialized inside the class definition.
For example, if
FailCount were const you could write in the class definition:
1 2
|
private:
const static int FailCount = 3;
|