So I'm a noob with programming, and I am unsure why I am unable to make a static variable in my class? I got a question from class and I'm not sure if I'm going about it the right way. The question is: Create a class with a static member item so that whenever a new object is created, the total number of objects of the class can be reported.
This is my code so 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 for class ObjectCount: " << objectNo << std::endl;
}
int main()
{
ObjectCount firstObject;
firstObject.reportObjectNo();
ObjectCount secondObject;
secondObject.reportObjectNo();
ObjectCount thirdObject;
thirdObject.reportObjectNo();
return 0;
}
And the error I get back is:
ISO C++ forbids in-class initialization of non-const static member 'objectNo'
line 9
I sincerely apologize if this has already been asked, but I couldn't find anything that helped me, if there is a link would be appreciated :)