Hi all,

I have a application which is completely written in C++. I got one review comment that normal class methods should not have any static variables and i am advised to move that variable inside class.

I want to know what will be advantage of keeping the static variables inside class?

Please provide suggestions.


Personally, I'd agree with whoever reviewed your code.

If you have any accessor functions in your class which allow other modules to get/set the values of these statics, you should promote them to be static class members and declare them in the header file for your class.

Otherwise if they are only used internally by your class, you should declare them in the classes unnamed namespace in your implementation (.cpp) file. This will localise them to the class/module in which they are declared.

Moving the static declarations out of the member functions where they're used and into the unnamed namespace will keep all of the internally used statics grouped together, so readers/maintainers of the .cpp file can see all of the statics which are used internally by the module.

Also, keeping these internal statics out of the class declaration in the header file aids in hiding complexity/implementation details. That is, hiding details that clients/users of the class do not need to know about. Not in the sense of hiding trade secrets or anything. This is more to do with only exposing things in the header file that clients/users of the class NEED to know about.

So things like static variables, constants or functions which are only used internally by the class are ideal candidates for putting into the unnamed namespace in the implementation/.cpp file. Clients/users of the class do not need to know about these in the header. The most important thing to clients/users is the public section of the class declaration, which lists the available external interfaces to the class.

Not sure if I've explained this entirely correctly, but I think you get the general idea!

This article has been dead for over six months. Start a new discussion instead.