friend class with limited access

It depends on what you mean by “a nice way” 🙂 At comp.lang.c++.moderated we had the same question a while ago. You may see the discussion it generated there.

IIRC, we ended up using the “friend of a nested key” approach. Applied to your example, this would yield:

class A
{
};

class B
{
public:
     class Key{
         friend class A;
         Key();
     };

    void setFlags(Key){setFlags();}         

private:
  void setState();
  void setFlags();
};

The idea is that the public setFlags() must be called with a “Key”, and only friends of Key can create one, as its ctor is private.

Leave a Comment