I want to make class A friend of class B. I want to do this as these interact very much and A needs to change internals of class B (which I don't want to expose using public). But I want to make sure it has access to only a few selected functions, not all the functions.
Example:
class A
{
};
class B
{
private:
void setState();
void setFlags();
friend class A;
};
I want A to be able to access setState
but not setFlags
... Is there a design pattern or a nice way of doing this, or am I left with giving full access or no access at all in this case?
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 setState(Key){setState();}
private:
void setState();
void setFlags();
};
The idea is that the public setState()
must be called with a "Key", and only friends of Key can create one, as its ctor is private.