I'm trying to understand how static ints work within classes, and I've fallen on some code that I don't quite understand how the answers come out to be what they are showing.

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

class CDummy {
    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;

Output is:


How in the world, are they getting these results!?! I see that n=0 and a.n refers to that value (static int). Is b[5] and array that holds five values? If so, how does "a.n" become 7? And how then, does CDummy::n = 6?

When you declare a data member static there is a single copy of that data member used by all instances of the class so a.n and CDummy::n refer to the same variable.

CDummy::n is incremented every time a class is constructed and decremented when the class is destroyed. So the first cout 7 classes have been created, a, the 5 in the array b and the one newed that c points to, the constructor has been called 7 times and CDummy::n incremented 7 times from 0 to 7.

The c is deleted, the destructor is called and n is decremented so at the next cout CDummy::n has a value of 6 (7 - 1).

commented: Excellent explanation - Thank you! +1

I will try to be succinct:

1. a static member variable acts like a single common variable
that is a global
so there is only really one 'n' in the whole project

2. a constructor () is called every time the computer has to allocate memory and give an address to a variable


//n = 0
CDummy a; //same as CDummy a() first  
//n +=1 
CDummy b[5];// creates 5 cdummies
 so CDummy is called once per slot = 5
n += 5;
CDummy * c = new CDummy(); //an obvious constrcutor
//n += 1

finally the dsstructor is called when the parameter is finished wuth
on delete of a pointer
or end of scope

{//start of scope
CDummy d;
 if(x == 7)
}//end of scope //d is destroyed


delete c;
//destructor called once as not delete[]
n -=1

add line


to your constructor and destructor and see results.