classes

hay guys, im having trouble with this code in the toutorial
// 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;
}

but it outputs 7 and then 6, shouldnt it output 0? i mean how is the static variable increased from 0 to 7 and then 6? pls help
w8 is it like everytime we declare something with type CDummy, n increases? and then when something of that type is deleted n is decreased? if so u someone explain to me properly hoe the ~ operator works?
Remember that constructors are called every time an object is created, and destructors are called every time an object is destroyed.

1
2
3
4
5
6
class CDummy {
public:
static int n;
CDummy () { n++; };  // this is the constructor
~CDummy () { n--; };  // this is the destructor
};


Every time the constructor is called (when an object is created), 'n' increments by 1. Every time the destructor is called (when an object is destroyed), 'n' decrements by 1.

1
2
3
4
5
6
7
8
9
10
int CDummy::n=0;  // n starts at zero

int main () {
CDummy a;  // this creates an object.  n is incremented by 1.  n==1
CDummy b[5];  // this creates 5 objects.  n is incremented 5 times
        // once for each object.  n==6
CDummy * c = new CDummy;  // this creates another object.  n==7
cout << a.n << endl;  // this prints 7
delete c;  // this destroys an object.  n==6
cout << CDummy::n << endl;  // this prints 6 



EDIT:

it's not really about the ~ operator... it's about ctors and dtors.

I think you skipped over an important section of the tutorial.

http://cplusplus.com/doc/tutorial/classes/ <-- see section on constructors and destructors.
Last edited on
Topic archived. No new replies allowed.