Static data members are declared in class. They are defined outside the class.
Thus in the class definition
class test {
public:
static int n;
test () { n++; };
~test () { n--; };
};
record
static int n;
only declares n. You need to define it that is to allocate memory for it.
And this
int test::n=0;
is its definition. test::n
is a qualified name of the variable that denotes that n belongs to class test.
According to the class definition when an object of the class is constructed this static variable is increased
test () { n++; };
And when an object is destructed this static variable is decreased
~test () { n--; };
In fact this static variable plays a role of counting alive objects of the class.
Thus in main you defined object of the class with name a
test a;
Each time an object is defined the constructor of the class is called. Consequently n was increased and becomes equal to 1.
Adter defining array of 5 objects
test b[5];
n becomes equal to 6.
After dynamically allocating one more object
test * c = new test;
n becomes equal to 7.
After its explicit deleting
delete c;
n again becomes equal to 6 because called destructor decreased n.