Reputation: 23
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 :)
Upvotes: 1
Views: 745
Reputation: 1495
C++ lets you declare and define in your class body only static const integral types.
class Foo
{
static const int xyz = 1;
};
non-const static member variables must be declared in the class and then defined outside of it.you define it in implementation file ie .cpp
int ObjectCount::objectNo = 0;
Also, the proper way to use it would be
ObjectCount::objectNo++;
since, objectNo is associated with class and not with any object.
Upvotes: 0
Reputation: 11561
The error message is telling you that you cannot initialize a non-const
static
member from inside a class. This would mean that you would need to change the code to look something more like:
class ObjectCount
{
public:
ObjectCount();
void reportObjectNo();
private:
static int objectNo;
};
int ObjectCount::objectNo = 0;
Upvotes: 2