Skip to content

Instantly share code, notes, and snippets.

@Mashpoe
Created November 13, 2022 08:27
Show Gist options
  • Save Mashpoe/dfc34622eece6727511c53820d0d953f to your computer and use it in GitHub Desktop.
Save Mashpoe/dfc34622eece6727511c53820d0d953f to your computer and use it in GitHub Desktop.
Hide private members from a friend class
#include <iostream>
// forward declare Foo so we can make it a friend of FooPrivate
class Foo;
// allows us to hide instance members from friends of Foo,
// but still allows Foo itself to access them.
class FooPrivate
{
private:
friend class Foo;
// only allow Foo to derive from this class
FooPrivate() {};
// hidden from friends of Foo
int x = 0;
};
// this class hides some of its private members from friend classes
class Foo : public FooPrivate
{
public:
int getX()
{
return x;
}
private:
// give Bar access to private method
friend class Bar;
void setX(int value)
{
x = value;
}
};
class Bar
{
public:
void modifyFoo(Foo& foo)
{
foo.setX(5);
// error: 'x' is a private member of 'FooPrivate'
//foo.x = 4;
}
};
int main()
{
Foo foo;
// prints "0"
std::cout << foo.getX() << std::endl;
Bar bar;
bar.modifyFoo(foo);
// prints "5"
std::cout << foo.getX() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment