Static variable for counting objects in C ++ classes?

I would like the static member variable to keep track of the number of objects that were made. For example:

class test{ static int count = 0; public: test(){ count++; } } 

This does not work because, according to VC ++, a member with an in-class initializer must be constant . Therefore, I looked around and, apparently, you should have done:

 test::count = 0; 

Which would be great, but I want count to be private.

change Oh boy I just realized what I need to do:

 int test::count = 0; 

I saw something just test::count = 0 , so I assumed that you would not have to declare the type again.

I would like to know if there is a way to do this inside the class.

edit2:

What I use:

 class test{ private: static int count; public: int getCount(){ return count; } test(){ count++; } } int test::count=0; 

Now he says: 'test' followed by 'int' is illegal (did you forget a ';'?)

Edit3:

Yup, forgot the semicolon after class definition. I'm not used to doing this.

+7
source share
3 answers

Placed

 static int count; 

In the header in the class definition and

 int test::count = 0; 

In the .cpp file. It will still be closed (if you leave an ad 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 a definition in one source file so that the linker knows which memory cell you are accessing when using the name test::count .

+10
source

Initialization of a static variable inside a function is allowed, so the solution may 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 method, you can bypass the C ++ restriction regarding the initialization of a static member in a declaration.

+2
source

static class members must be defined (and potentially initialized) in the namespace area, member access rules are not applied.

+1
source

All Articles