Reputation: 10939
Is there a way to force a class/enum to only be accessible in the same file, similar to how static functions/variables behave?
// free-floating static function
// basically I want similar access restrictions on helper-type classes/enums
static void func(void)
{
}
// this is a compiler error
static class A
{
};
Upvotes: 3
Views: 138
Reputation: 206518
Just declare them within an Unnamed namespace.
Note that usage of static
to limit the scope of variables to the same translation unit is limited by the fact that it can be only applied to variable declarations and functions, but not to the user-defined types.
Unnamed namespaces remove this disadvantage and allow you to define user defined types in the scope of same translation unit.
From linked MSDN:
Unnamed namespaces are a superior replacement for the static declaration of variables. They allow variables and functions to be visible within an entire translation unit, yet not visible externally. Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit.
Upvotes: 7
Reputation: 7092
A class declared inside an Unnamed namespace is what you want:
namespace
{
class SomeClass { };
}
This will be named mangled in such a way by the compiler that it is inaccessible outside of that translation unit.
Upvotes: 9