Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can some one explain what is taking place with this code:

C++
// 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;
}


Your assistance is much appreciated.
Posted
Updated 2-Mar-12 9:16am
v2

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.
 
Share this answer
 
Comments
wayten 3-Mar-12 13:08pm    
Thanks John. Your explanation has given a much clearer understanding of the program.
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:

C++
// 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;
}
 
Share this answer
 
Comments
wayten 4-Mar-12 10:24am    
Thanks Emilio
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900