Search code examples
javac++namespaces

Namespace-private members in C++


I'm reading Scott Meyers C++ and now I'm at the section about encapsulation. He said that there's no way to encapsulate data-members unless to declare them private. And that's clear.

But since I came from Java having its package-private methods and members, I'm interested in if C++ allows us to do some tricks to declare some in a namespace so that it's inaccessible outside of the namespace. Namespace-private or something like that. I thought that the following code using anonymous-namespace would be fine:

namespace A {
    namespace { //anonymous namespace within the namespace
        int a;
    }
    void foo(){ std::cout << a << std::endl; }
}

int main()
{
    A::a = 2;
    A::foo();
}

But it worked fine: http://coliru.stacked-crooked.com/a/b4690b9bb28dad29


Solution

  • I'm interested in if C++ allows us to do some tricks to declare some in a namespace so that it's inaccessible outside of the namespace.

    You cannot have a private namespace where the C++ language itself will enforce its privacy and keep it inaccessible to the outside world in the same way that private members are.

    If anything, it would have to be done by adopting a consistent naming convention within the specific codebase.

    This is, in a way, similar to how Python method names are prefixed with a leading underscore _ as a convention to indicate that the method (or data member) is considered "private" and shouldn't be accessed from the outside.