I have a class that has 5 static public functions and 1 static private function (called from one of the public functions). The class doesn't have any member variables. It seems to me that it should be a namespace and not a class. But what to do with the private function? I prefer it not to be accessible by every namespace user, but there is no access control in namespaces.
Making a function a static member of a class rather than a free function gives two advantages: It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function; It associates the function with the class in a similar way to a namespace.
A process can create a private namespace using the CreatePrivateNamespace function.
Can Static Functions Be Virtual in C++? In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class.
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.
There are two ways i know of
One way is to not declare those functions inside the header. They can be placed into unnamed namespaces within the implementation file, only.
Indeed, you will then have to implement any function that accesses this private function in the implementation file (not inline in the header).
Preferably, you put them in a different header, and include them. So the code of them won't disturb your interface header. This is how boost
does it, too:
#include "detail/destroy.hpp"
namespace orbit {
void destroy() {
detail::destroy_planets();
detail::destroy_stars();
}
}
I don't think there is a solution to this :)
One -different- solution, would be to separate these functions into a separate compilation unit, then declare the private functions inside an anonymous namespace.
Keep the public declaration in the header file. Move the implementations to a cpp file. Mark previously private
methods as static
. This will make them unaccessible from a different linker objects (compilation units) and effectively hide them.
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