// MyClass.h
namespace MyNamespace {
static const double GasConstant = 1.987;
class MyClass
{
// constructors, methods, etc.
};
}
I previously had GasConstant declared within the MyClass declaration (and had a separate definition in the source file since C++ does not support const initialization of non-integral types). I however need to access it from other files and also logically it seems like it should reside at the namespace level.
My questions is, what effect does static const have in this case? Clearly const means I can’t assign a new value to GasConstant, but what does a static member at the namespace mean. Is this similar to static at file scope, where the member is not accessible outside of the unit?
The use of
staticat namespace scopeiswas* deprecated in C++. It would normally only ever be seen in a source file, where its effect is to make the variable local to that source file. That is, another source file can have a variable of exactly the same name with no conflict.In C++, the recommended way to make variables local to the source file is to use an anonymous namespace.
I think it’s fair to say the
staticin the header in your code is simply incorrect.*As pointed out by Tom in the comments (and in this answer), the C++ committee reversed the decision to deprecate
staticuse at file scope, on the basis that this usage will always be part of the language (e.g. for C compatibility).