Initializing static class members

If I try to initialize obj_s , he asks me to do it const - and I cannot do this because I need to consider the number of my objects created.

 #include<iostream> class A { static int obj_s=0; public: A(){ ++obj_s;cout << A::obj_s << "\nObject(s) Created\n"; } }; int main() { A a,b,c,d; } 

The following error is saved in the code below:

  [Linker error] undefined reference to `A::obj_s' 
+1
source share
1 answer

[solvable]

The code gives an error, because the object is not created in the second case, and in the first it is not initialized, as it was supposed to be - Here is the fixed code:

 #include<iostream> class A { static int obj_s; public: A() { obj_s++; std::cout << A::obj_s << "\nObject(s) Created\n" ; } }; int A::obj_s=0; // This is how you intialize it int main() { A a ,b,c,d; } 
+5
source

All Articles