Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
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;
}
 
Your assistance is much appreciated.
Posted 2-Mar-12 10:12am
wayten336
Edited 2-Mar-12 10:16am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  
Comments
wayten at 3-Mar-12 13:08pm
   
Thanks John. Your explanation has given a much clearer understanding of the program.
Rate this: bad
good
Please Sign up or sign in to vote.

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;
}
  Permalink  
Comments
wayten at 4-Mar-12 10:24am
   
Thanks Emilio
Rate this: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 7,903
1 Sergey Alexandrovich Kryukov 7,127
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,820


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 10 Mar 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100