I have a .cpp
file which has some static free functions. I know how that would help in a header file, but since the cpp is not included anywhere, what's the point? Are there any advantages to it?
Declaring a function as static prevents other files from accessing it. In other words, it is only visible to the file it was declared in; a "local" function. You could also relate static (function declaration keyword, not variable) in C as private in object-oriented languages.
You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.
Absolutely yes. The non-static member functions are meant to cater the non-static member variables. If variables are not used then the function should be made static which makes your design cleaner and you can avoid passing this as the 1st hidden argument (which betters the performance a little).
Declaring free functions as static
gives them internal linkage, which allows the compiler more aggressive optimizations, as it is now guaranteed that nobody outside the TU can see that function. For example, the function might disappear entirely from the assembly and get inlined everywhere, as there is no need to provide a linkable version.
Note of course that this also changes the semantics slightly, since you are allowed to have different static functions of the same name in different TUs, while having multiple definitions of non-static functions is an error.
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