Is there a way to have a static member variable of a class and have it increment every time an object of that class is instantiated so that I know how many objects of that class are created.
I think I used to do this in Java, but I can't seem to be able to do it in C++.
so I have class:
1 2 3 4 5 6 7
class Asteroid
{
public:
void incrementNumOfAsteroids();
private:
staticint numOfAsteroids = 0;
}
Then in the implementation have something like this
It has nothing to do with initialization. The static declaration inside the class is just that -- its a declaration, not an instantiation. You have to instantiate the variable somewhere.
Statics are initialized to zero by default -- there is no need to make the explicit assignment as mikeglaz did. (Though it doesn't hurt -- in fact, I do it too).
The reason the line exists is for everything else but the "= 0" part. It instantiates the variable.