12,062,966 members (31,829 online)
Rate this:
See more:
Can some one explain what is taking place with this code:

```// static members in classes
#include <iostream>
using namespace std;

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

int CDummy::n=0;

int main ()
{
CDummy a;
CDummy b[5];
CDummy * c = new CDummy;
cout << a.n << endl;
delete c;
cout << CDummy::n << endl;
return 0;
}```

Posted 2-Mar-12 10:12am
wayten336
Edited 2-Mar-12 10:16am
v2

Rate this:

## Solution 1

It's illustrating the nature of a static variable in a class. No matter how many instances of the class are created, the value of n is shared among them.
wayten 3-Mar-12 13:08pm

Thanks John. Your explanation has given a much clearer understanding of the program.
Rate this:

## Solution 2

`static int n` is a variable that exist for the entire life of the program and is incremented / decremented upon the creation / destruction of CDummy.

As a consequence it tells the number of existing CDummy.

The main creates one, then 5 all together, then another on the heap, prints the number, destroy one (the one on the heap), prints again the number (one less as before) and - on return - destroy all the others.

A good variant can be this one:

```// static members in classes
#include <iostream>
using namespace std;

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

int CDummy::n=0;

int main ()
{
cout << Dummy::n << endl;  //0
{
CDummy a;
{
cout << Dummy::n << endl; //1
CDummy b[5];
CDummy * c = new CDummy;
cout << Dummy::n << endl; //7
}
cout << a.n << endl; //2
delete c;
}
cout << CDummy::n << endl; //0
return 0;
}```
wayten 4-Mar-12 10:24am

Thanks Emilio
Rate this:

## Solution 4

n is class share the static veriables shared betweenthem the address,and static veriables are global addr,the address will not be changed;my understanding.

Top Experts
Last 24hrsThis month
 Dave Kreskowiak 337 CHill60 300 d@nish 175 Chris Maunder 135 Garth J Lancaster 120
 Dave Kreskowiak 1,827 Richard MacCutchan 1,225 d@nish 980 OriginalGriff 800 Sergey Alexandrovich Kryukov 733