Search code examples
c++oopprivate-membersaccess-specifier

Fine grained access specifiers c++


I have the following class :-

class A {
  public:
    // some stuff that everyone should see
  protected:
    // some stuff that derived classes should see
  private:
    // some stuff that only I can see
    void f();
    void g();
};

Now, I want f() to only be accessible from a certain set of classes (say classes B,C,D) and g() to be accessible from a certain other set of classes (say classes D,E,F). Is there any way to specify this in C++? If I make all the classes friends of A, then both f & g will be accessible from B,C,D,E,F (along with the other private members of A) which is not what I want.

Is this possible or should I change my object model?


Solution

  • class A_f {
        friend class B;
        void f();
    };
    
    class A_g {
        friend class C;
        void g();
    };
    
    class A: public A_f, public A_g {
        friend class A_f;
        friend class A_g;
    private:
        void do_f();
        void do_g();
    };
    
    inline void A_f::f() { static_cast<A *>(this)->do_f(); }
    inline void A_g::g() { static_cast<A *>(this)->do_g(); }
    
    void B::something(A *a) {
        a->f();
    }