Search code examples
c++classscopestatictranslation-unit

c++ How to declare a class as local to a file


So, I know static functions are functions that are local to the file. Thus, they can't be accessed from other files. Does this work for classes too? I've read a ton of controversy on how static class does not declare the class to contain purely static members and methods (which is obvious), but couldn't find anything that mentioned whether or not this would declare the class to be locally accessible to the file scope, as is more logical.

In case it doesn't, what about using an anonymous namespace, which I've heard also can be used to declare file local functions?


Solution

  • You can define a class in unnamed namespace as for example

    namespace
    {
        struct A {};
    }
    

    In this case the class name will have internal linkage. That is it is visible only in the compilation unit where it is defined and all compilation units that include that definition will have their own class definitions.

    As for the storage class specifier static then (7.1.1 Storage class specifiers)

    5 The static specifier can be applied only to names of variables and functions and to anonymous unions