class - Creating static variables in classes (C++) -


so i'm noob programming, , unsure why unable make static variable in class? got question class , i'm not sure if i'm going right way. question is: create class static member item whenever new object created, total number of objects of class can reported.

this code far:

#include <iostream>  class objectcount { public:     objectcount();     void reportobjectno();  private:     static int objectno = 0;  };   objectcount::objectcount() {     objectno++; }  void objectcount::reportobjectno() {     std::cout << "number of object created class objectcount: " << objectno << std::endl; }  int main() {     objectcount firstobject;     firstobject.reportobjectno();      objectcount secondobject;     secondobject.reportobjectno();      objectcount thirdobject;     thirdobject.reportobjectno();     return 0; } 

and error is:

iso c++ forbids in-class initialization of non-const static member 'objectno' line 9 

i sincerely apologize if has been asked, couldn't find helped me, if there link appreciated :)

the error message telling you cannot initialize non-const static member inside class. mean need change code more like:

class objectcount { public:     objectcount();     void reportobjectno();  private:     static int objectno;  };  int objectcount::objectno = 0; 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -