I have a bit confusion about inheritance and friendship. Consider this example:
class D;
class A
{
protected:
int x = 0;
private:
int y = 1;
public:
int z = 2;
friend class D;
};
class B : public A
{};
class C : protected A
{};
class D
{
public:
void f(B b){cout << b.x << b.y << b.z << endl;} // ok
void f2(C c){cout << c.x << c.y << c.z << endl;} // error
};
f(B b)
is straightforward becauseb
can access all the members ofA
becauseclass D
is afriend
ofclass A
.But why
f2(C c)
doesn't compile? in factC
inheritsprotectedly
fromA
andD
is a friend ofA
so whyf
compiles andf2
doesn't? and how Derivation Access Specifier affect this? Thank you!
The output:
In member function ‘void D::f2(C)’: ../main.cpp:34:27: error: ‘int A::x’ is protected within this context 34 | void f2(C c){cout << c.x << c.y << c.z << endl;} // error | ^ ../main.cpp:16:8: note: declared protected here 16 | int x = 0; | ^ ../main.cpp:34:34: error: ‘int A::y’ is private within this context 34 | void f2(C c){cout << c.x << c.y << c.z << endl;} // error | ^ ../main.cpp:18:8: note: declared private here 18 | int y = 1; | ^ ../main.cpp:34:41: error: ‘int A::z’ is inaccessible within this context 34 | void f2(C c){cout << c.x << c.y << c.z << endl;} // error | ^ ../main.cpp:20:8: note: declared here 20 | int z = 2; | ^