0

I have a question which is basically the quite opposite of this one.

As we can see in this post, Java does have one more access mode than C++ : package one.
In my code, I would like to make a class that only some other class could instantiate and use, from its own namespace, and not outside. So it looks like a Java "package-privacy access" case, but this option is not available in C++.

UML Diagram

My idea to implement it is to make constructor/destructor and most of methods of this class as private or protected, and to give access to other classes from the same namespace with friend keyword.
But, almost everywhere on forums as on my personal talks with other C++ programmers, friend is considered as an evil keyword that destroy every OOP concept and should never be used.

Would it be adequate to use it in this precise case ? Or is there any other solution without friend use ?

Community
  • 1
  • 1
Aracthor
  • 5,757
  • 6
  • 31
  • 59
  • If you want only one other class to use it, then why not make it a private nested class of the one that uses it? – eerorika Sep 02 '15 at 13:28
  • @user2079303 I might use it in more than one class in the same namespace. I edited the diagram. – Aracthor Sep 02 '15 at 13:33
  • 1
    `friend is considered as an evil keyword that destroy every OOP concept and should never be used` --- this is simply not true. Besides, OOP is not the be all and end all for everyone. Namespaces are open, everyone can add a class of their own to any namespace (except std), which is why namespace-level access would be meaningless. – n. m. could be an AI Sep 02 '15 at 13:36

1 Answers1

0

When you use friend you won't be able to restrict access to anything private (e.g. member variables).

I may have a better solution. You define a struct with a private constructor that defines all classes in your "package" as friend. Then you change the constructor(s) of the classes you want to restrict in access from outside the package to take a reference to that object.

#include <iostream>
#include <vector>


struct code_unlocker
{
    friend struct A;
    friend struct B;
    friend struct C;
private:
    code_unlocker() {};
};

struct A
{
    A(const code_unlocker&)  //Restricted: Only callabble by friends of code_unlocker
    {
    };
};


struct B
{
    B(const code_unlocker&)  //Restricted: Only callabble by friends of code_unlocker
    {
        A a = A(code_unlocker());  //Works
    };
};


struct C
{
    C()//Accessible from outside
    {
        B b = B(code_unlocker()); //Works
    };
};

using namespace std;
int main(int, char *[])
{
    A a = A(code_unlocker()); //Doesn't work
    B b = B(code_unlocker()); //Doesn't work
    C c = C(); //Works

}
Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49