Reputation: 173
This is an over simplification of what I am working with because there is a lot of code. So I have two classes. A is the parent of Aa and X is the parent of Xx. I set the parent A as a friend class of X and Xx so that I can access its private and protected variables . Now because Aa is the child of A and inherits from A why can't I access the protected members of X or Xx? A is a friend class so shouldn't this work? I always get an error saying that barA
is a protected member of X.
class A {
friend class X;
friend class Xx;
public:
void FooA();
protected:
int fooA;
};
class Aa: public A {
public:
voif Fooa();
private:
int fooa;
};
class X {
public:
void BarA();
protected:
int barA;
};
class Xx: public X {
public:
void Bara();
private:
int bara;
};
Upvotes: 3
Views: 4294
Reputation: 206607
You said,
I set the parent A as a friend class of X and Xx so that I can access its private and protected variables .
This is a wrong understanding of what friend
does to classes. Take a human comparison to make more sense of it.
Say you trust your friend John. You give him the keys to your house. With that John come in and out of your house as he pleases. You made John a "friend". However, that does not give you access to John's house. John hasn't given the key to his house to you. He hasn't granted you the "friend"-ship that you have granted him.
In your case, A
has granted friend
-ship to X
and Xx
. X
and Xx
can easily access private sections of A
. This does not give A
access to the private sections of X
and Xx
. Only X
and Xx
can grant that friend
-ship -- by declaring
friend class A;
in the class definition.
Upvotes: 0
Reputation: 75565
Friendship is not inherited and one-way. You will have to make the subclass a friend
also.
Also, in your current declarations, X
can access private members of A
, but not vice versa.
As the other answer said, you will need to add friend class Aa;
to class X
.
If you want A
also to have access to members of X
, then you need to add friend class A;
into X
as well.
Upvotes: 0
Reputation: 30489
When you write friend class X;
and friend class Xx;
it means member functions of X and Xx can access private and protected members of class A. It seems you want the reverse. For that you should add friend class Aa
in class X and Xx.
Upvotes: 5