Let’s say I have two classes Foo and Bar, and I want to make Foo friends with Bar without changing Foo. Here’s my attempt:
class Foo
{
public:
Foo(){}
private:
void privateFunction(){}
};
template <class friendly, class newFriend>
class friends : public friendly
{
private:
friend newFriend;
};
class Bar
{
public:
Bar(){}
void callFriendlyFunction()
{
friendlyFoo.privateFunction();
}
private:
friends<Foo, Bar> friendlyFoo;
};
int main(int argc, char* argv[])
{
Bar bar;
bar.callFriendlyFunction();
return 0;
}
Getting a compiler error about trying to call a private function, so apparently it didn’t work. Any ideas?
It doesn’t work, because
friendshas no access toprivateFunctionanyway, because it’sprivate(descendant classes have no access to private fields anyway). If you would declareprivateFunctionasprotected, it would work.Here’s a nice paper about Mixins in C++. (PDF link)