Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 812
Daniel Santos Avatar asked Aug 05 '16 17:08

Daniel Santos


People also ask

Can you declare a private class in a namespace?

Private. You can use Private only at module level. This means you can declare a private element inside a module, class, or structure, but not at the level of a source file or namespace, inside an interface, or in a procedure.

Can namespaces have private members?

No, Allowing classes to be private to a namespace would achieve no meaningful level of protection. Because private means that the member is only access in the containing class. Since a top-level class has no class containing it; it cannot be private or protected.

Can classes be private in C#?

Class, record, and struct accessibilityClass members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private . Class and struct members, including nested classes and structs, have private access by default.

How do you make a class private in C++?

Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class.


1 Answers

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.

like image 113
rahnema1 Avatar answered Oct 10 '22 17:10

rahnema1