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
}
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With