0
class test {
public:
    static int n;
    test () { n++; };
    ~test () { n--; };
};

int test::n=0; //<----what is this step called? how can a class be declared as an integer?

int main () {
    test a;
    test b[5]; // I'm not sure what is going on here..is it an array?
    test * c = new test;
    cout << a.n << endl;
    delete c;
    cout << test::n << endl;
}

secondly, the output is 7,6 I'm not understanding how did it get 7, from where?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • https://www.google.com/search?q=c%2B%2B+static+member+initialization&ie=utf-8&oe=utf-8&aq=t&rls=Palemoon:en-US&client=palemoon – user3528438 May 02 '15 at 20:05

2 Answers2

2

From the statement-

int test::n=0; 

'::' is called scope resolution operator. This operator is used here to initialize the static field n, not the class

Razib
  • 10,965
  • 11
  • 53
  • 80
1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335