I would like to have a static member variable keep track of the amount of objects that have been made. Like so:
class test{
static int count = 0;
public:
test(){
count++;
}
}
That doesn’t work because, according to VC++, a member with an in-class initializer must be constant. So I looked around and apparently you’re supposed to do:
test::count = 0;
Which would be great, but I want count to be private.
edit:
Oh boy, I just realized I need to do:
int test::count = 0;
I had seen something just do test::count = 0, so I assumed you wouldn’t have to declare type again.
I’d like to know if there’s a way to do this inside the class though.
edit2:
What I’m using:
class test{
private:
static int count;
public:
int getCount(){
return count;
}
test(){
count++;
}
}
int test::count=0;
Now it’s saying: 'test' followed by 'int' is illegal (did you forget a ';'?)
edit3:
Yup, forgot a semicolon after the class definition. I’m not used to having to do that.
Put
In your header in the class definition, and
In the .cpp file. It will still be private (if you leave the declaration in the header in the private section of the class).
The reason you need this is because
static int countis a variable declaration, but you need the definition in a single source file so that the linker knows what memory location you’re referring to when you use the nametest::count.