Search code examples
c++oopclassc++11friend

Friend declaration for single member instead of whole class?


Normally in C++ when class A declares friendship with class B, class B has full access to class A private members. What I need to do is to allow class B to access only one private member of class A and nothing else. Is there any way for it, maybe something new in C++11?


Solution

  • Not that I'm aware of. If it's really important to only allow access to a single member, you could wrap the data in another class (C) that has entirely private members, make that class a friend of B and provide a public accessor for the C object in A.

    Something like this:

    template<class T> class MatesWithB
    {
         friend class B;
    
      public:
         MatesWithB( T & val ) : data(val) {}
    
      private:
         T& data;
         operator T&()             { return data; }
         operator const T&() const { return data; }
    };
    
    class A
    {
          // ...
          MatesWithB<int> GetPrivateThingy() { return MatesWithB(thingy); }
    
       private:
          int thingy;            // Shared with class B
    };
    

    Something like that. I haven't run this through a compiler to check.

    But I just wonder... When you find yourself needing to do this, isn't something in your design fundamentally flawed?