Daniel Santos
Daniel Santos

Reputation: 15808

How make a class private inside a namespace in C++?

How make a class private inside a namespace in C++ and prevent other to access the class from outside the namespace, for instance:

namespace company{
    class MyPublicClass{ ... }  // This should be accessible 
    class MyPrivateClass{ ... } // This should NOT be accessible
}

Upvotes: 7

Views: 9167

Answers (3)

rahnema1
rahnema1

Reputation: 15837

You can use unnamed namespace. Names that appear in an unnamed namespace have internal linkage but names that appear in a named namespace and don't have any storage class specifier, by default, have external linkage.

For example we have a file named source1.cpp:

//source1.cpp
namespace company{
    class MyPublicClass{ ... };
    namespace{
        class MyPrivateClass{ ... };
    }
}
void f1(){
company::MyPrivateClass m;
}

MyPublicClass has external linkage and MyPrivateClass has internal linkage. So there is no problem with source1 and it can be compiled as a library ,but if we have other file named source2.cpp:

//source2.cpp
void f2(){
company::MyPrivateClass m;
}

source2 can't be linked with the compiled source1 and we can not refer to MyPrivateClass.

Upvotes: 14

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You cannot.

C++ namespaces don't provide any scoped accessors, neither do class declarations (vs C# for example).

The usual way is to introduce an internal namespace to indicate public usage isn't intended.

You may restrict access using friend specifiers.

You can also use some tricks, to make it harder accessing an interface publicly like explained here: How can I remove/refactor a «friend» dependency declaration properly?

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409176

You can't have access specifiers for namespaces, but you can for classes:

class company {
    // Private (default)
    class MyPrivateClass { ... };

public:
    class MyPublicClass { ... };
};

You access the classes just like for a namespace with the scope operator:

company::MyPublicClass my_public_object;

If the "public" class should have access to the "private" class, then the "private" class have to be a friend of the `public" class.


There is also another way, and that is to simply not have the MyPrivateClass definition in a public header file. Either define the class in the source file, or in a private header file only included internally.

Which way to choose depends on your design and use-cases.

Upvotes: 11

Related Questions