As we know a private
member is inaccessible (not just private) in derived classes while public
and protected
are directly accessible there.
- If a class declares another class as a
friend
then the latter has full-access to the members of the first.
Here is an example I've tried to understand but in vain:
class A
{
public:
int pub;
private:
int priv;
protected:
int prot;
friend class D;
};
class B : public A // public inheritance
{
int b = 0;
};
class C : private A
{
int c = 0;
};
class D
{
public:
void foo(B);
void bar(C);
};
void D::foo(B b)
{
b.pub = 0;
b.prot = 0;
b.priv = 0; // why this works? although A::priv is inaccessible in derived classes because it is private in base class?
// b.b = 0; // error. ok because b is private
}
void D::bar(C c)
{
// c.pub = 0; // error ok
// c.prot = 0; // error ok
// c.priv = 0; // error ok
// c.c = 0; // error. ok because c is private
}
- The problem: Why
D::foo
can access private member ofA
through an object from apublic
ly inherited from BaseA
although we knowprivate
is inaccessible in derived classes? so whyb.priv = 0;
works? We know thatfriendship
is neither transitive nor inherited?