I tried to count the number of instances of a class using :
class shelf
{
private:
static int count_instances = 0 ;
book b1;
public :
shelf() {
count_instances++;
cout << "this is the "<<count_instances<<" instance"<<endl;
}
};
main (){
shelf s1;
}
but get the compilation error : ISO c++ forbids in-class initialization of non-const static member.
While the following arrangement seems to work
class shelf
{
private:
static int count_instances ;
book b1;
public :
shelf() {
count_instances++;
cout << "this is the "<<count_instances<<" instance"<<endl;
}
};
int shelf::count_instances =0;
main (){
shelf s1;
}
Can someone help me understand? Also what is the right way to count the number of instances of a class