I was wondering if it was possible to restrict access to certain functions or objects declared in a namespace exclusively to other classes in the same file. For instance,
//myheader.h
namespace stuff
{
int repair(firstObj obj);
int doSomethingElse();
privateObj obj;
}
In this case, I want the function doSomethingElse()
and the object obj
to be accessible to classes declared in this file only.
Is there some keyword I could use to restrict access?
use an unnamed namespace:
namespace stuff
{
int repair(firstObj obj);
namespace
{
int doSomethingElse();
privateObj obj;
}
}
From here [emphasis mine]:
Unnamed namespaces are a superior replacement for the static declaration of variables. They allow variables and functions to be visible within an entire translation unit, yet not visible externally. Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit.
See also this related question: Unnamed/anonymous namespaces vs. static functions
Edit: Just noted that it's a header file we're talking about:
In this case, I want the function doSomethingElse() and the object obj to only be accessible to classes declared in this file.
Then you shouldn't declare these methods and objects in a public header file in the first place, but rather in the specific implementation file: If other shall not use them, other should not even know they'd exist.
And then use an unnamed namespace to effectively restrict the reachability (e.g. if someone would accidentally provide another declaration using the same identifier).
If you leave it in the header file, this could happen: anonymous namespaces and the one definition rule (if the header is included in more than one translation unit):
Yes, put it in an anonymous namespace:
namespace stuff
{
int repair(firstObj obj)
namespace
{
int doSomethingElse();
privateObj obj;
}
}
declare them as static
this means that they will only be accessible within that file.
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