Suppose that I have these classes:
class Bar;
class Foo {
private:
// stuff here
public:
void methodForClassBar();
};
What I want to do is make methodForClassBar
private in a way that class Bar
still be able to call it. But I don't want class Bar
to be able to access any other private members of Foo
.
My current solution is this: put methodForClassBar
into private, and create an accessor class (FooInterfaceToClassBar
, this can only be accessed by Bar
), which is a friend to Foo
. So with this accessor class, I can call methodForClassBar
:
class FooInterfaceToClassBar;
class Foo {
private:
// stuff here
private:
void methodForClassBar();
friend FooInterfaceToClassBar;
};
class FooInterfaceToClassBar {
private:
static void inline callMethod(Foo &foo) {
foo.methodForClassBar();
}
friend class Bar;
};
void Bar::someMethod(Foo &foo) {
FooInterfaceToClassBar::callMethod(foo);
}
Is there a other/better (more convenient) method to achieve this, without any runtime performance cost (I'd like to avoid adding interfaces with virtual methods)?