I am an object-oriented programming enthusiast at a beginner level. I have encountered the following puzzle:
class A {
};
class B {
protected:
friend class A;
};
class C {
public:
friend class B;
};
Referring to the sample code above, assuming the above classes had data members, what names of C’s members could be used in declarations of members of A?
-
Only private members
-
Only protected members
-
All of C’s data members
-
Only public members
-
None of C’s data members*
My choice is answer 4 as friendship is not transitive. Therefore, A is a friend of B, but A is not a friend of C (even though B is a friend of C).
Is that correct thinking?
Also, my issue is that so far (in the tutorial) I’ve met exmaples in which friendship was declared like this:
class X {
public:
friend class Y;
};
What is the difference if instead of the public specifier we use the protected one? Like that:
class X {
protected:
friend class Y;
};
frienddeclaration.As long as class
Aitself is not declared friend of classC. You cannot access any protected or private members ofCinA.