Search code examples
c++classfriend

How to make a class able to access only certain private members of another class?


Suppose we have two classes:

class Base
{
private:
    int x;
public:
    void f();
};

class Foo
{
    // some variables and methods
};

Now everyone can call Base::f(), but I want only Foo to be able to do so.

In order to achieve this effect, we can make Base::f() private and declare Foo as a friend:

class Base
{
private:
    int x;
    void f();
    friend Foo;
};

The problem with this approach is that Foo has the access to both Base::f() and Base::x (and even to any other private members of Base). But I want Foo to have access only to Base::f().

Is there a way for a class (or a function) to grant an access only to certain private members of another class? Or maybe anyone could suggest a better approach to my problem?

EDIT:

I'll try to specify the access restriction I need. Firstly, Base is an interface in a library (it's an abstract class, in fact). The user uses only the classes derived from Base. Base::f() is called only by Foo which is another class in the library. Hiding Base::f() from the user is important, because only Foo knows when to call it. At the same time, Foo shouldn't mess up the other members of Base.


Solution

  • Very hacky, but this will allow very fine grained access.

    class Base
    {
    private:
        int x;
        void f();
        friend class Base_f_Accessor;
    };
    
    class Base_f_Accessor
    {
    private:
        static void f(Base & b) { b.f(); }
        friend class Foo;
    }
    
    class Foo
    {
        // some variables and methods
    };