Can we achieve encapsulation using namespace in c++ ? Or is it compiler dependent ?
Yes, you can achieve a degree of encapsulation using namespaces.
The obvious limitation is that you can't create instances of namespaces, so the things you encapsulate in a namespace won't normally support instances either. So, if you want to encapsulate something like "how was the program configured to run", a namespace probably works fine. If you want to encapsulate data you're going to store about each item in a database of items, chances are that a namespace isn't going to be much (if any) help.
To truly restrict access to data, you have to use namespaces in conjunction with other features. In particular, names in an anonymous namespace are visible (without qualification) to code in the same translation unit--but are completely invisible outside that translation unit.
// A.cpp
namespace {
int foo;
}
int bar() {
// this code has free access to foo
}
// B.cpp
int baz() {
// this code has no access to foo
}
So in this case, we've encapsulated access to foo
, so only the code in A.cpp
can access it. Much like with a member of a class, code in A.cpp can also pass a reference or pointer to foo
to some other code outside A.cpp, to give it access to foo
.