Codesmith
Codesmith

Reputation: 6752

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?

Upvotes: 13

Views: 5274

Answers (2)

2785528
2785528

Reputation: 5566

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.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

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

Upvotes: 33

Related Questions