Uday0119
Uday0119

Reputation: 790

How to restrict the visibility of a class outside the namespace in which it is declared?

I have a namespace in c++ which contains 5 classes. All of them are having public access modifier. Out of these, 2 classes are static classes.

I want to restrict these classes to be visible outside the namespace in which they are declared.

So, like in another namespace, if I import this namespace, then these 2 classes should not be available to use.

Upvotes: 2

Views: 2842

Answers (3)

AlexTheo
AlexTheo

Reputation: 4184

There are 2 possibilities to prevent using classes in c++, first one is to make these classes private and nested inside the class where you go to use them.

class User{
private:
  class Internal{};
};

The second possibility is to make the constructor of your class private and declare the friend classes which will be able to use it like:

class Internal{
private:
 friend class User;
 Internal(){}
public:
 //class interface.
};

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361722

There aren't static classes in C++. If by static classes you mean helper classes used by other classes in your code, and are not meant to be used by client code, then you can use unnamed namespace, and define the helper classes inside them.

namespace somespace
{
    namespace   //it is unnamed namespace
    {
           class helper
           {
               //define it here
           };
    }
    class A
    {
          helper m_helper;
    };
}

Boost uses another technique as well. It defines all the helper classes in a namepace called details.

namespace somespace
{
    namespace details  //it is details namespace
    {
           class helper
           {
               //define it here
           };
    }
    class A
    {
          details::helper m_helper;  //use fully-qualified name
    };
}

Upvotes: 3

mareb
mareb

Reputation: 11

I would try to put the two static classes in another namespace and make this namespace useable in the implemention files of the other 5 classes. More ideas possible, if you give minimal example source.

Upvotes: 1

Related Questions