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.
This is because the static variable retains the value after the increment even when the function block ends. Data segments are used to allocate a static variable and not stack segments. Static variables by default have some values with which it is initialized if not explicitly initialized.
What is a Static Variable? In programming, a static variable is the one allocated “statically,” which means its lifetime is throughout the program run. It is declared with the 'static' keyword and persists its value across the function calls.
Put
static int count;
In your header in the class definition, and
int test::count = 0;
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 count
is 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 name test::count
.
Initialization of static variable within a function is allowed so a solution can be something like this
class test
{
private:
static int & getCount ()
{
static int theCount = 0;
return theCount;
}
public:
int totalCount ()
{
return getCount ();
}
test()
{
getCount () ++;
}
};
in general using this technique it is possible to work around the C++ limitation regarding static member initialization in the declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With