can anyone explain this simple code to me

// 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;


why is the result for the answer 7 and 6,
I think it keeps track of how many instances of class CDummy are currently active.
For instance if you declare 3 CDummys, and 1 of them later goes out of scope, the value of n would be 2.
Last edited on
the constructors (CDummy () { n++; }) increment the static variable in the class every time they create an object and the destructors (~CDummy () { n--; }) de-increment that same variable every time they destroy an object.

1
2
3
4
5
6
CDummy a; // +1
CDummy b[5]; // +5
CDummy * c = new CDummy; //+1
cout << a.n << endl; // = 7
delete c; // -1
cout << CDummy::n << endl; // = 6 


forgot to say that the static variable declared in the class has global scope for this class meaning that only one is created. so every time an object of this class changes the value of this static variable only that one is altered. in other words each class object does not contain it's own seperate static variable. this allows it's value to be global known at all times and helps with keep track of things, like how many objects created / destroyed, etc.
Last edited on
Topic archived. No new replies allowed.