13

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?

Codesmith
  • 5,779
  • 5
  • 38
  • 50

2 Answers2

32

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Does this work for classes too?

No. no such 'static' keyword for class.


As an alternative to an 'anonymous namespace', you can declare a class (Foo) and its definition (implementation) entirely within a single cpp file. The only code which can use this class is the code below that declaration ...

File X.cpp:

// Foo declared
class Foo
{
public:
   //...ctor
   //...dtor
   // etc.       
}

// ... Foo defined (implemented)
Foo::etc() { ... }


// implementation of X - only X has access to Foo.

End of X.cpp.

And File X.hpp does not reference Foo.

If you subsequently discover a name collision (i.e. linker reports duplicate symbol), your only choice is to change one or the other name.


There are many Q&A's in SO about anonymous namespaces. I am careful what kinds of things I put into one, and agree they can prevent name collision.

I have used both techniques.

2785528
  • 5,438
  • 2
  • 18
  • 20
  • 1
    My current compiler (Intel) does NOT warn about duplicate classes, as long as the methods don't overlap. If you have two files (X.cpp and Y.cpp) and both of them declare a local `class Foo`, at linkage time, the linker will pick a hybrid of either declaration! It's a total mess. – Mark Lakata Jan 09 '20 at 21:32
  • this method can bite you when you add templates that use that class and this class NAME-template combination is used somwhere else – Kikaxa Nov 18 '20 at 20:30