Prz3m3k
Prz3m3k

Reputation: 605

Class friendship - a puzzle

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?

  1. Only private members

  2. Only protected members

  3. All of C's data members

  4. Only public members

  5. 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; 
};

Upvotes: 9

Views: 235

Answers (1)

Alok Save
Alok Save

Reputation: 206656

  1. You are correct. Friendship is not transitive nor is it Inherited.
  2. It does not make any difference under what access specifier you put the friend declaration.

As long as class A itself is not declared friend of class C. You cannot access any protected or private members of C in A.

Upvotes: 7

Related Questions