Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
};
like image 881
Prz3m3k Avatar asked Jan 17 '13 12:01

Prz3m3k


1 Answers

  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.

like image 69
Alok Save Avatar answered Nov 12 '22 11:11

Alok Save