How to make a class available only to some 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 to be Fooable to do it.

To achieve this effect, we can make Base::f()private and declare Fooas a friend:

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

The problem with this approach is that it Foohas access both to Base::f()and to Base::x(and even to any other private members Base). But I want Fooonly access to Base::f().

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

EDIT:

, . -, Base - ( ). , Base. Base::f() Foo, . Base::f() , Foo , . Foo Base.

+5
4

, .

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
};
+6

, Base :

class BaseData {
protected:
    int x;
};

class Base : public BaseData {
    friend class Foo;
    void f ();
};

Foo f Base, , x. . protected, x , , BaseData.

Base Foo , Base.

class With_f {
    friend class Foo;
protected:
    virtual void f () = 0;
};

class With_g {
protected:
    virtual void g () = 0;
};

class Base : public With_f, public With_g {
    int x;
    void f () {}
    void g () {}
};

Foo With_f Base, f. Foo g.

+4

, - . ++ . , , . , - .

+2

, , , , . :

#include <iostream>

class Nesting
{
  friend class Foo;
  class Nested1
  {
    friend class Nesting;
  public:
    Nested1() : i(3) { }
  private:
    int i;
  } n1;
  class Nested2
  {
    friend class Nesting;
    friend class Foo;
  public:
    Nested2() : j(5) { }
  private:
    int j;
  } n2;
  int f() { return n1.i; }
};

class Foo
{
public:
  Foo(Nesting& n1) : n(n1) { }
  int getJ() { return n.n2.j + n.f(); }
private:
  Nesting& n;
};

int main()
{
  Nesting n;
  Foo foo(n);
  std::cout << foo.getJ() << "\n";
}
0

All Articles