confusing interplay between static members and constructors
Hello Kohinoor24!
Graham: Comments right on, as usual!
Kohinoor24: Please study the following sample program.
I think it will help you to understand the interplay between static member variables and class constructors. Please note that your class constructor will be called for every instance of the class CycleBuffer, every time, without concern for whatever static member variables are defined within the class. The constructor is always called. A static member variable in C++ can be initialized once, for example, in an initialization statement or in a line of code which is guaranteed to run one single time and before the contents of the static variable are needed elsewhere. Each modification of the static is carried out on the single instance of the static.
Try to initialize your static at one point in your entire program and use it consistently throughout the program. See sample program below.
Best regards.
Chris.
#include <iostream>
using namespace std;
class A
{
public:
A() { ++the_static; }
private:
static int the_static;
public:
friend void print_a(const A& a);
};
int A::the_static = 1234;
void print_a(const A& a)
{
cout << a.the_static << endl;
}
int main(int argc, char* argv[])
{
A a1;
print_a(a1);
A a2;
print_a(a2);
return 1;
}
:)