Reputation: 7636
//static member 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;
}
The result is 7, 6. Can anybody explain it for me? and I don't understand this "CDummy b[5];". People never use syntax like this in C, right? what is this here? Thank you!
Upvotes: 0
Views: 152
Reputation: 1587
n
is a static member variable in class CDummy
. n is associated with all objects of the class rather than each object instance of the class.
n
is incremented as each object instance gets created and decremented as each object instance is destroyed.
In the main function we create object a (n=1), followed by array of objects b of size 5 (n=6) followed by pointer to object c (n=7). So the first cout
statement output 7. As object pointed to by c is destroyed n is decremented to 6.
So the second cout
statement outputs 6.
Please refer to this link for details on static members in a class
Upvotes: 0
Reputation: 67195
CDummy b[5]
is just an array of 5 CDummy objects.
A static member means there is only one instance of that member no matter how many instances are made of the class.
The class simply increments n from the constructor whenever a new instance is initialized, and decrements n from the destructor whenever the instance is destroyed. It's basically tracking how many instances of this class are currently active.
Upvotes: 0
Reputation: 2372
static on this situation mean that the variable n is the same for all instances of CDummy, in your case a, b and c (after you allocate the object using new) all share the same n. Thats why you see this value.
CDummy b[5] -> this declares an array of CDummy, on this case 5 CDummys.
Upvotes: 0
Reputation: 21541
CDummy b[5]
is an array of five CDummy
objects. CDummy a
is simply a single instance of CDummy
, and so is CDummy c
.
Every time a CDummy
is created, the constructor is called.
Let's add that up: 5 + 1 + 1 = 7
. That's why n
was initially 7
. When c
was deleted, n--
was executed, and n
became 6
.
Upvotes: 1
Reputation: 355019
CDummy b[5];
This declares an array of five CDummy
objects. It ends up calling the CDummy
default constructor five times (once for each object in the array).
You create seven CDummy
objects: a
, five in the array b
, and the one pointed to by c
. n
then has a value of 7
. Then you destroy one CDummy
object (the one pointed to by c
) and n
has a value of 6
. The remaining six CDummy
objects are destroyed when they go out of scope when the main
function returns.
Upvotes: 2