Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict access to certain functions or objects to current file?

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?

like image 859
user1553248 Avatar asked Aug 02 '12 17:08

user1553248


3 Answers

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):

like image 120
moooeeeep Avatar answered Nov 09 '22 11:11

moooeeeep


Yes, put it in an anonymous namespace:

namespace stuff
{
    int repair(firstObj obj)

    namespace
    {
        int doSomethingElse();
        privateObj obj;
    }
}
like image 5
Mark B Avatar answered Nov 09 '22 12:11

Mark B


declare them as static this means that they will only be accessible within that file.

like image 2
John Corbett Avatar answered Nov 09 '22 12:11

John Corbett