// static members in classes
#include <iostream>
usingnamespace std;
class CDummy {
public:
staticint m;
staticint 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;
system("pause");
return 0;
}
This is the code i copy from the tutorial, there are few things which i am not sure what they do.
1 2 3 4 5 6 7
CDummy a; // the class has a constructor, so when declared, the n is added by 1?
CDummy b[5];// this is add n by 5? This is very confusing...
CDummy * c = new CDummy; // So the constructor will also run when a pointer
// of the class is declared?
CDummy a; // the class has a constructor, so when declared, the n is added by 1?
yes
CDummy b[5];// this is add n by 5? This is very confusing...
it creates a 5 element array
CDummy * c = new CDummy; // So the constructor will also run when a pointer
// of the class is declared?
thats simply a dynamic object created with "new"
No, the other way round. You can create new objects during runtime (with new) and the constructor of the object will indirectly increase the n. The n variable shouldn't be public but private so it can only be accessed by functions of the class (in this case usually constructor and destructor).
CDummy b[n]; would be wrong for that
CDummy* myPointer = new CDummy[k];
would be correct where k is the amount of objects u want to have.
Since the constructor of each object increases n by one the above statement will increase n by k